repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
tracee/contextlogger | integration-test/testcontextprovider/src/main/java/io/tracee/contextlogger/integrationtest/testcontextprovider/TestContextDataWrapper.java | 1634 | package io.tracee.contextlogger.integrationtest.testcontextprovider;
import io.tracee.contextlogger.contextprovider.api.ProfileConfig;
import io.tracee.contextlogger.contextprovider.api.TraceeContextProvider;
import io.tracee.contextlogger.contextprovider.api.TraceeContextProviderMethod;
import io.tracee.contextlogger.contextprovider.api.WrappedContextData;
/**
* Test wrapper class that wraps type {@link io.tracee.contextlogger.integrationtest.WrappedTestContextData}.
*/
@TraceeContextProvider(displayName = "testdata", order = 50)
@ProfileConfig(basic = true, enhanced = true, full = true)
public class TestContextDataWrapper implements WrappedContextData<WrappedTestContextData> {
public static final String PROPERTY_NAME = "io.tracee.contextlogger.integrationtest.testcontextprovider.TestContextDataWrapper.output";
private WrappedTestContextData contextData;
public TestContextDataWrapper() {
}
public TestContextDataWrapper(final WrappedTestContextData contextData) {
this.contextData = contextData;
}
@Override
public void setContextData(Object instance) throws ClassCastException {
this.contextData = (WrappedTestContextData) instance;
}
@Override
public WrappedTestContextData getContextData() {
return this.contextData;
}
@Override
public Class<WrappedTestContextData> getWrappedType() {
return WrappedTestContextData.class;
}
@SuppressWarnings("unused")
@TraceeContextProviderMethod(displayName = "testoutput", order = 10)
@ProfileConfig(basic = false, enhanced = true, full = true)
public String getOutput() {
return contextData != null ? contextData.getOutput() : null;
}
}
| bsd-3-clause |
zellerdev/jabref | src/test/java/org/jabref/logic/layout/format/AuthorLastFirstAbbreviatorTester.java | 1833 | package org.jabref.logic.layout.format;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test case that verifies the functionalities of the formater AuthorLastFirstAbbreviator.
*/
class AuthorLastFirstAbbreviatorTester {
/**
* Verifies the Abbreviation of one single author with a simple name.
* <p/>
* Ex: Lastname, Name
*/
@Test
void testOneAuthorSimpleName() {
assertEquals("Lastname, N.", abbreviate("Lastname, Name"));
}
/**
* Verifies the Abbreviation of one single author with a common name.
* <p/>
* Ex: Lastname, Name Middlename
*/
@Test
void testOneAuthorCommonName() {
assertEquals("Lastname, N. M.", abbreviate("Lastname, Name Middlename"));
}
/**
* Verifies the Abbreviation of two single with a common name.
* <p/>
* Ex: Lastname, Name Middlename
*/
@Test
void testTwoAuthorsCommonName() {
String result = abbreviate("Lastname, Name Middlename and Sobrenome, Nome Nomedomeio");
String expectedResult = "Lastname, N. M. and Sobrenome, N. N.";
assertEquals(expectedResult, result);
}
@Test
void testJrAuthor() {
assertEquals("Other, Jr., A. N.", abbreviate("Other, Jr., Anthony N."));
}
@Test
void testFormat() {
assertEquals("", abbreviate(""));
assertEquals("Someone, V. S.", abbreviate("Someone, Van Something"));
assertEquals("Smith, J.", abbreviate("Smith, John"));
assertEquals("von Neumann, J. and Smith, J. and Black Brown, P.",
abbreviate("von Neumann, John and Smith, John and Black Brown, Peter"));
}
private String abbreviate(String name) {
return new AuthorLastFirstAbbreviator().format(name);
}
}
| mit |
luiz787/portal-educacao | Banco de Questões/java/UI/InserirVouF.java | 51535 | /*
* 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 UI;
import bancodequestoes.Alternativa;
import bancodequestoes.ConexaoBD;
import bancodequestoes.Imagem;
import bancodequestoes.VOuF;
import java.awt.Color;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* @author Paiva Morais
*/
public class InserirVouF extends javax.swing.JFrame {
/** Define se esta é uma janela de edição ou de inserção */
private boolean editar;
/** Se a imagem for para ser editada pega o ID dela */
private int idEditar;
/**
* Creates new form Inserir
*/
public InserirVouF() {
initComponents();
}
/**
* Caso a janela sirva para editar a questão
* @param VouF O objeto da antiga questão
* @param idEditar o id da questão editada
*/
public InserirVouF(VOuF VouF, int idEditar){
initComponents();
editar = true;
this.idEditar = idEditar;
this.disciplinaVouF.setSelectedItem(VouF.getMateria());
this.temaVouF.setText(VouF.getMateria());
this.temaVouF.setForeground(new Color(0,0,0));
this.dificuldadeVouF.setSelectedIndex(VouF.getDificuldade());
this.enunciadoVouF.setText(VouF.getEnunciado());
this.enunciadoVouF.setForeground(new Color(0,0,0));
this.aleatorioCHK.setState(VouF.isAleatoria());
//Esse é um daqueles codigos que vou ficar com vegonha dps mas..
//Pega a alternativas
for (Alternativa alternativa : VouF.getAlternativas()) {
if(this.alt1vouf.getText().equals("DIGITE O TEXTO AQUI.")){
this.alt1vouf.setText(alternativa.getTexto());
this.alt1vouf.setForeground(new Color(0,0,0));
if(alternativa.IsCorreta()){
this.alt1verdadeiro.setSelected(true);
} else this.alt1verdadeiro.setSelected(false);
} else if(this.alt2vouf.getText().equals("DIGITE O TEXTO AQUI.")){
this.alt2vouf.setText(alternativa.getTexto());
this.alt2vouf.setForeground(new Color(0,0,0));
if(alternativa.IsCorreta()){
this.alt2verdadeiro.setSelected(true);
} else this.alt2verdadeiro.setSelected(false);
} else if(this.alt3vouf.getText().equals("DIGITE O TEXTO AQUI.")){
this.alt3vouf.setText(alternativa.getTexto());
this.alt3vouf.setForeground(new Color(0,0,0));
if(alternativa.IsCorreta()){
this.alt3verdadeiro.setSelected(true);
} else this.alt3verdadeiro.setSelected(false);
} else if(this.alt4vouf.getText().equals("DIGITE O TEXTO AQUI.")){
this.alt4vouf.setText(alternativa.getTexto());
this.alt4vouf.setForeground(new Color(0,0,0));
if(alternativa.IsCorreta()){
this.alt4verdadeiro.setSelected(true);
} else this.alt4verdadeiro.setSelected(false);
} else if(this.alt5vouf.getText().equals("DIGITE O TEXTO AQUI.")){
this.alt5vouf.setText(alternativa.getTexto());
this.alt5vouf.setForeground(new Color(0,0,0));
if(alternativa.IsCorreta()){
this.alt5verdadeiro.setSelected(true);
} else this.alt5verdadeiro.setSelected(false);
} else if(this.alt6vouf.getText().equals("DIGITE O TEXTO AQUI.")){
this.alt6vouf.setText(alternativa.getTexto());
this.alt6vouf.setForeground(new Color(0,0,0));
if(alternativa.IsCorreta()){
this.alt6verdadeiro.setSelected(true);
} else this.alt6verdadeiro.setSelected(false);
} else if(this.alt7vouf.getText().equals("DIGITE O TEXTO AQUI.")){
this.alt7vouf.setText(alternativa.getTexto());
this.alt7vouf.setForeground(new Color(0,0,0));
if(alternativa.IsCorreta()){
this.alt7verdadeiro.setSelected(true);
} else this.alt7verdadeiro.setSelected(false);
}
}
}
/**
* 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() {
seletorArq = new javax.swing.JFileChooser();
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
buttonGroup4 = new javax.swing.ButtonGroup();
buttonGroup5 = new javax.swing.ButtonGroup();
buttonGroup6 = new javax.swing.ButtonGroup();
buttonGroup7 = new javax.swing.ButtonGroup();
jScrollPane2 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
homeVouF = new javax.swing.JButton();
disciplinaVouF = new javax.swing.JComboBox<>();
temaVouF = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
dificuldadeVouF = new javax.swing.JComboBox<>();
jLabel10 = new javax.swing.JLabel();
enviarVouF = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
enunciadoVouF = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
alt1vouf = new javax.swing.JTextField();
alt2vouf = new javax.swing.JTextField();
alt3vouf = new javax.swing.JTextField();
alt4vouf = new javax.swing.JTextField();
alt5vouf = new javax.swing.JTextField();
alt6vouf = new javax.swing.JTextField();
alt7vouf = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
alt1verdadeiro = new javax.swing.JRadioButton();
alt1falso = new javax.swing.JRadioButton();
alt2verdadeiro = new javax.swing.JRadioButton();
alt2falso = new javax.swing.JRadioButton();
alt3verdadeiro = new javax.swing.JRadioButton();
alt3falso = new javax.swing.JRadioButton();
alt4verdadeiro = new javax.swing.JRadioButton();
alt5verdadeiro = new javax.swing.JRadioButton();
alt6verdadeiro = new javax.swing.JRadioButton();
alt4falso = new javax.swing.JRadioButton();
alt5falso = new javax.swing.JRadioButton();
alt6falso = new javax.swing.JRadioButton();
alt7falso = new javax.swing.JRadioButton();
alt7verdadeiro = new javax.swing.JRadioButton();
labelImagem = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
imagemBTN = new javax.swing.JButton();
desfazerImagem = new javax.swing.JButton();
aleatorioCHK = new java.awt.Checkbox();
seletorArq.setFileSelectionMode(JFileChooser.FILES_ONLY);
seletorArq.setFileFilter(new FileNameExtensionFilter("JPG Images", "jpg"));
seletorArq.setAcceptAllFileFilterUsed(false);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane2.setToolTipText("");
jScrollPane2.setPreferredSize(new java.awt.Dimension(1028, 516));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setPreferredSize(new java.awt.Dimension(1028, 865));
jLabel7.setFont(new java.awt.Font("Trebuchet MS", 0, 48)); // NOI18N
jLabel7.setForeground(new java.awt.Color(1, 87, 155));
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel7.setText("Banco de Questões");
jLabel7.setToolTipText("Banco de Questões");
jLabel7.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
jLabel7.setAlignmentX(0.5F);
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
homeVouF.setBackground(new java.awt.Color(33, 150, 243));
homeVouF.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
homeVouF.setForeground(new java.awt.Color(255, 255, 255));
homeVouF.setText("HOME");
homeVouF.setToolTipText("Ir para o inicio");
homeVouF.setAlignmentX(0.5F);
homeVouF.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
homeVouF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
homeVouFActionPerformed(evt);
}
});
disciplinaVouF.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
disciplinaVouF.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Defina a disciplina:", "Aplicações para Web", "Arquitetura de Sistemas Digitais", "Linguagem de Programação - JAVA", "Manutenção de Computadores", "Biologia", "Filosofia", "Física", "Geografia", "História", "Matemática", "Português", "Química", "Sociologia", "Outra" }));
disciplinaVouF.setToolTipText("Defina a disciplina da questão");
temaVouF.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
temaVouF.setForeground(new java.awt.Color(153, 153, 153));
temaVouF.setText("DIGITE O TEXTO AQUI.");
temaVouF.setToolTipText("Defina o tema");
temaVouF.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
temaVouFFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
temaVouFFocusLost(evt);
}
});
jLabel9.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
jLabel9.setForeground(new java.awt.Color(153, 153, 153));
jLabel9.setText("Digite o tema:");
jLabel9.setToolTipText("Defina o tema");
dificuldadeVouF.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
dificuldadeVouF.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Defina o nível de dificuldade da questão:", "Fácil", "Mediana", "Díficil" }));
dificuldadeVouF.setToolTipText("Defina a dificuldade");
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(homeVouF, javax.swing.GroupLayout.PREFERRED_SIZE, 531, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(temaVouF)
.addComponent(disciplinaVouF, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(dificuldadeVouF, javax.swing.GroupLayout.PREFERRED_SIZE, 975, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 43, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(homeVouF, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(disciplinaVouF, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(temaVouF, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(dificuldadeVouF, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jLabel10.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel10.setText("A ferramenta que produz provas de maneira simples e funcional");
jLabel10.setToolTipText("Descrição");
enviarVouF.setBackground(new java.awt.Color(33, 150, 243));
enviarVouF.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
enviarVouF.setForeground(new java.awt.Color(255, 255, 255));
enviarVouF.setText("ENVIAR");
enviarVouF.setToolTipText("Enviar Imagem pro BD");
enviarVouF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
enviarVouFActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
jLabel1.setForeground(new java.awt.Color(153, 153, 153));
jLabel1.setText("Digite o enunciado da questão:");
jLabel1.setToolTipText("Defina o enunciado");
enunciadoVouF.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
enunciadoVouF.setForeground(new java.awt.Color(153, 153, 153));
enunciadoVouF.setText("DIGITE O TEXTO AQUI.");
enunciadoVouF.setToolTipText("Defina o enunciado");
enunciadoVouF.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
enunciadoVouFFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
enunciadoVouFFocusLost(evt);
}
});
jLabel3.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
jLabel3.setForeground(new java.awt.Color(153, 153, 153));
jLabel3.setText("Digite as alternativas:");
jLabel3.setToolTipText("defina as alternativas");
alt1vouf.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
alt1vouf.setForeground(new java.awt.Color(153, 153, 153));
alt1vouf.setText("DIGITE O TEXTO AQUI.");
alt1vouf.setToolTipText("Defina uma alternativa");
alt1vouf.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
alt1voufFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
alt1voufFocusLost(evt);
}
});
alt2vouf.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
alt2vouf.setForeground(new java.awt.Color(153, 153, 153));
alt2vouf.setText("DIGITE O TEXTO AQUI.");
alt2vouf.setToolTipText("Defina uma alternativa");
alt2vouf.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
alt2voufFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
alt2voufFocusLost(evt);
}
});
alt3vouf.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
alt3vouf.setForeground(new java.awt.Color(153, 153, 153));
alt3vouf.setText("DIGITE O TEXTO AQUI.");
alt3vouf.setToolTipText("Defina uma alternativa");
alt3vouf.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
alt3voufFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
alt3voufFocusLost(evt);
}
});
alt4vouf.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
alt4vouf.setForeground(new java.awt.Color(153, 153, 153));
alt4vouf.setText("DIGITE O TEXTO AQUI.");
alt4vouf.setToolTipText("Defina uma alternativa");
alt4vouf.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
alt4voufFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
alt4voufFocusLost(evt);
}
});
alt5vouf.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
alt5vouf.setForeground(new java.awt.Color(153, 153, 153));
alt5vouf.setText("DIGITE O TEXTO AQUI.");
alt5vouf.setToolTipText("Defina uma alternativa");
alt5vouf.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
alt5voufFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
alt5voufFocusLost(evt);
}
});
alt6vouf.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
alt6vouf.setForeground(new java.awt.Color(153, 153, 153));
alt6vouf.setText("DIGITE O TEXTO AQUI.");
alt6vouf.setToolTipText("");
alt6vouf.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
alt6voufFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
alt6voufFocusLost(evt);
}
});
alt7vouf.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
alt7vouf.setForeground(new java.awt.Color(153, 153, 153));
alt7vouf.setText("DIGITE O TEXTO AQUI.");
alt7vouf.setToolTipText("Defina uma alternativa");
alt7vouf.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
alt7voufFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
alt7voufFocusLost(evt);
}
});
jLabel4.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
jLabel4.setText("Verdadeiro");
jLabel5.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
jLabel5.setText("Falso");
alt1verdadeiro.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup1.add(alt1verdadeiro);
alt1verdadeiro.setToolTipText("Defina se ela é verdadeira");
alt1falso.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup1.add(alt1falso);
alt1falso.setSelected(true);
alt1falso.setToolTipText("Defina se ela é falsa");
alt2verdadeiro.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup2.add(alt2verdadeiro);
alt2verdadeiro.setToolTipText("Defina se ela é verdadeira");
alt2falso.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup2.add(alt2falso);
alt2falso.setSelected(true);
alt2falso.setToolTipText("Defina se ela é falsa");
alt3verdadeiro.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup3.add(alt3verdadeiro);
alt3verdadeiro.setToolTipText("Defina se ela é verdadeira");
alt3falso.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup3.add(alt3falso);
alt3falso.setSelected(true);
alt3falso.setToolTipText("Defina se ela é falsa");
alt4verdadeiro.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup4.add(alt4verdadeiro);
alt4verdadeiro.setToolTipText("Defina se ela é verdadeira");
alt5verdadeiro.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup5.add(alt5verdadeiro);
alt5verdadeiro.setToolTipText("Defina se ela é verdadeira");
alt6verdadeiro.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup6.add(alt6verdadeiro);
alt6verdadeiro.setToolTipText("Defina se ela é verdadeira");
alt4falso.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup4.add(alt4falso);
alt4falso.setSelected(true);
alt4falso.setToolTipText("Defina se ela é falsa");
alt5falso.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup5.add(alt5falso);
alt5falso.setSelected(true);
alt5falso.setToolTipText("Defina se ela é falsa");
alt6falso.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup6.add(alt6falso);
alt6falso.setSelected(true);
alt6falso.setToolTipText("Defina se ela é falsa");
alt7falso.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup7.add(alt7falso);
alt7falso.setSelected(true);
alt7falso.setToolTipText("Defina se ela é falsa");
alt7verdadeiro.setBackground(new java.awt.Color(255, 255, 255));
buttonGroup7.add(alt7verdadeiro);
alt7verdadeiro.setToolTipText("Defina se ela é verdadeira");
labelImagem.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
labelImagem.setForeground(new java.awt.Color(153, 153, 153));
labelImagem.setText("CAMINHO DA IMAGEM:");
labelImagem.setToolTipText("O caminho da imagem no seu computador");
jLabel6.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
jLabel6.setForeground(new java.awt.Color(153, 153, 153));
jLabel6.setText("Selecione uma imagem para a questão(opcional):");
jLabel6.setToolTipText("Defina a imagem da questão");
imagemBTN.setBackground(new java.awt.Color(33, 150, 243));
imagemBTN.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
imagemBTN.setForeground(new java.awt.Color(255, 255, 255));
imagemBTN.setText("SELECIONAR IMAGEM");
imagemBTN.setToolTipText("Selecionar imagem");
imagemBTN.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
imagemBTNActionPerformed(evt);
}
});
desfazerImagem.setBackground(new java.awt.Color(153, 153, 153));
desfazerImagem.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
desfazerImagem.setForeground(new java.awt.Color(255, 255, 255));
desfazerImagem.setText("DESFAZER");
desfazerImagem.setEnabled(false);
desfazerImagem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
desfazerImagemActionPerformed(evt);
}
});
aleatorioCHK.setLabel("Alternativas Aleatorias");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, 1028, Short.MAX_VALUE)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(aleatorioCHK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(alt2vouf, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
.addComponent(alt3vouf, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt4vouf, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt5vouf, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt6vouf, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt7vouf, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt1vouf))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt1verdadeiro)
.addComponent(alt2verdadeiro)
.addComponent(alt3verdadeiro)
.addComponent(alt4verdadeiro)
.addComponent(alt5verdadeiro)
.addComponent(alt6verdadeiro)
.addComponent(alt7verdadeiro))))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt1falso)
.addComponent(jLabel5)
.addComponent(alt2falso)
.addComponent(alt3falso)
.addComponent(alt4falso)
.addComponent(alt5falso)
.addComponent(alt6falso)
.addComponent(alt7falso))
.addGap(40, 40, 40))
.addComponent(enviarVouF, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(enunciadoVouF)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(labelImagem, javax.swing.GroupLayout.PREFERRED_SIZE, 540, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(imagemBTN, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(desfazerImagem, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(enunciadoVouF, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addComponent(aleatorioCHK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt1vouf, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(alt1verdadeiro))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt2vouf, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(alt2verdadeiro)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(alt1falso)
.addGap(18, 18, 18)
.addComponent(alt2falso)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt3vouf, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(alt3verdadeiro)
.addComponent(alt3falso))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt4vouf, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(alt4verdadeiro)
.addComponent(alt4falso))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt5vouf, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(alt5verdadeiro)
.addComponent(alt5falso))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt6vouf, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(alt6verdadeiro)
.addComponent(alt6falso))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alt7falso)
.addComponent(alt7vouf, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(alt7verdadeiro))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(13, 13, 13)
.addComponent(desfazerImagem, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelImagem)
.addComponent(imagemBTN, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(enviarVouF, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jScrollPane2.setViewportView(jPanel1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 943, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void homeVouFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_homeVouFActionPerformed
FormInicial home = new FormInicial();
home.setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_homeVouFActionPerformed
private void enviarVouFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enviarVouFActionPerformed
ConexaoBD conn = new ConexaoBD();
ArrayList<String> erros = new ArrayList();
ArrayList<Alternativa> alternativas = new ArrayList(5);
VOuF verdadeiroFalso = new VOuF();
if(disciplinaVouF.getSelectedIndex() == 0) erros.add("Disciplina não definida");
if(temaVouF.getText().trim().equals("")) erros.add("Não ha temas definidos");
if(dificuldadeVouF.getSelectedIndex() == 0) erros.add("Não ha dificuldade selecionada.");
if(enunciadoVouF.getText().trim().equals("")) erros.add("Não ha enunciado definido");
//Alternativas
if(!(alt1vouf.getText().trim().isEmpty())
&& !(alt2vouf.getText().trim().isEmpty())){
alternativas.add(new Alternativa(alt1vouf.getText().trim(),
alt1verdadeiro.isSelected()));
alternativas.add(new Alternativa(alt2vouf.getText().trim(), alt2verdadeiro.isSelected()));
if(!(alt3vouf.getText().trim().isEmpty())){
alternativas.add(new Alternativa(alt3vouf.getText().trim(), alt3verdadeiro.isSelected()));
}
if(!(alt4vouf.getText().trim().isEmpty())){
alternativas.add(new Alternativa(alt4vouf.getText().trim(), alt4verdadeiro.isSelected()));
}
if(!(alt5vouf.getText().trim().isEmpty())){
alternativas.add(new Alternativa(alt5vouf.getText().trim(), alt5verdadeiro.isSelected()));
}
if(!(alt6vouf.getText().trim().isEmpty())){
alternativas.add(new Alternativa(alt6vouf.getText().trim(), alt6verdadeiro.isSelected()));
}
if(!(alt7vouf.getText().trim().isEmpty())){
alternativas.add(new Alternativa(alt7vouf.getText().trim(), alt7verdadeiro.isSelected()));
}
} else {
erros.add("Não ha alternativas suficientes definidas.");
}
if(erros.isEmpty()){
verdadeiroFalso.setMateria(disciplinaVouF.getSelectedItem().toString());
verdadeiroFalso.setConteudo(temaVouF.getText().trim().replace(" ", ""));
verdadeiroFalso.setDificuldade((byte) dificuldadeVouF.getSelectedIndex());
verdadeiroFalso.setEnunciado(enunciadoVouF.getText().trim());
verdadeiroFalso.setAlternativas(alternativas);
verdadeiroFalso.setAleatoria(aleatorioCHK.getState());
if(!labelImagem.getText().equals("CAMINHO DA IMAGEM:")){
verdadeiroFalso.setImagem(new Imagem(labelImagem.getText()));
}
try {
if(editar){ //se for pra editar questão caso contrario insere
conn.editQuestaobd(idEditar, verdadeiroFalso);
JOptionPane.showMessageDialog(this, "Questão editada com sucesso "
+ "no banco.", "SUCESSO", JOptionPane.INFORMATION_MESSAGE);
} else {
conn.addQuestaobd(verdadeiroFalso);
JOptionPane.showMessageDialog(this, "Questão adicionada com sucesso "
+ "no banco.", "SUCESSO", JOptionPane.INFORMATION_MESSAGE);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Erro ao conectar ao banco de "
+ "dados. Cheque sua conexão.", "ERRO",
JOptionPane.ERROR_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "ERRO Ocorreu algum "
+ "erro de input.", "ERRO",
JOptionPane.ERROR_MESSAGE);
}
this.setVisible(false);
new FormInicial().setVisible(true);
} else{
String errorList = "";
for (String erro : erros) {
errorList += erro + "\n";
}
JOptionPane.showMessageDialog(this, errorList, "ERRO",
JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_enviarVouFActionPerformed
private void imagemBTNActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_imagemBTNActionPerformed
if(seletorArq.showOpenDialog(jPanel1) == 1){
JOptionPane.showMessageDialog(jPanel1, "Não foi selecionado nenum arquivo valido.");
}else{
labelImagem.setText(seletorArq.getSelectedFile().getAbsolutePath());
desfazerImagem.setBackground(new Color(33,150,243));
desfazerImagem.setEnabled(true);
}
}//GEN-LAST:event_imagemBTNActionPerformed
private void desfazerImagemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_desfazerImagemActionPerformed
desfazerImagem.setBackground(new Color(153,153,153));
desfazerImagem.setEnabled(false);
labelImagem.setText("CAMINHO DA IMAGEM:");
}//GEN-LAST:event_desfazerImagemActionPerformed
private void temaVouFFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_temaVouFFocusGained
if(temaVouF.getText().equals("DIGITE O TEXTO AQUI.")){
temaVouF.setText("");
temaVouF.setForeground(new Color(0,0,0));
}
}//GEN-LAST:event_temaVouFFocusGained
private void enunciadoVouFFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_enunciadoVouFFocusGained
if(enunciadoVouF.getText().equals("DIGITE O TEXTO AQUI.")){
enunciadoVouF.setText("");
enunciadoVouF.setForeground(new Color(0,0,0));
}
}//GEN-LAST:event_enunciadoVouFFocusGained
private void alt1voufFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt1voufFocusGained
if(alt1vouf.getText().equals("DIGITE O TEXTO AQUI.")){
alt1vouf.setText("");
alt1vouf.setForeground(new Color(0,0,0));
}
}//GEN-LAST:event_alt1voufFocusGained
private void alt2voufFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt2voufFocusGained
if(alt2vouf.getText().equals("DIGITE O TEXTO AQUI.")){
alt2vouf.setText("");
alt2vouf.setForeground(new Color(0,0,0));
}
}//GEN-LAST:event_alt2voufFocusGained
private void alt3voufFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt3voufFocusGained
if(alt3vouf.getText().equals("DIGITE O TEXTO AQUI.")){
alt3vouf.setText("");
alt3vouf.setForeground(new Color(0,0,0));
}
}//GEN-LAST:event_alt3voufFocusGained
private void alt4voufFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt4voufFocusGained
if(alt4vouf.getText().equals("DIGITE O TEXTO AQUI.")){
alt4vouf.setText("");
alt4vouf.setForeground(new Color(0,0,0));
}
}//GEN-LAST:event_alt4voufFocusGained
private void alt5voufFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt5voufFocusGained
if(alt5vouf.getText().equals("DIGITE O TEXTO AQUI.")){
alt5vouf.setText("");
alt5vouf.setForeground(new Color(0,0,0));
}
}//GEN-LAST:event_alt5voufFocusGained
private void alt6voufFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt6voufFocusGained
if(alt6vouf.getText().equals("DIGITE O TEXTO AQUI.")){
alt6vouf.setText("");
alt6vouf.setForeground(new Color(0,0,0));
}
}//GEN-LAST:event_alt6voufFocusGained
private void alt7voufFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt7voufFocusGained
if(alt7vouf.getText().equals("DIGITE O TEXTO AQUI.")){
alt7vouf.setText("");
alt7vouf.setForeground(new Color(0,0,0));
}
}//GEN-LAST:event_alt7voufFocusGained
private void temaVouFFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_temaVouFFocusLost
if(temaVouF.getText().equals("")){
temaVouF.setText("DIGITE O TEXTO AQUI.");
temaVouF.setForeground(new Color(153, 153, 153));
}
}//GEN-LAST:event_temaVouFFocusLost
private void enunciadoVouFFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_enunciadoVouFFocusLost
if(enunciadoVouF.getText().equals("")){
enunciadoVouF.setText("DIGITE O TEXTO AQUI.");
enunciadoVouF.setForeground(new Color(153, 153, 153));
}
}//GEN-LAST:event_enunciadoVouFFocusLost
private void alt1voufFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt1voufFocusLost
if(alt1vouf.getText().equals("")){
alt1vouf.setText("DIGITE O TEXTO AQUI.");
alt1vouf.setForeground(new Color(153, 153, 153));
}
}//GEN-LAST:event_alt1voufFocusLost
private void alt2voufFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt2voufFocusLost
if(alt2vouf.getText().equals("")){
alt2vouf.setText("DIGITE O TEXTO AQUI.");
alt2vouf.setForeground(new Color(153, 153, 153));
}
}//GEN-LAST:event_alt2voufFocusLost
private void alt3voufFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt3voufFocusLost
if(alt3vouf.getText().equals("")){
alt3vouf.setText("DIGITE O TEXTO AQUI.");
alt3vouf.setForeground(new Color(153, 153, 153));
}
}//GEN-LAST:event_alt3voufFocusLost
private void alt4voufFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt4voufFocusLost
if(alt4vouf.getText().equals("")){
alt4vouf.setText("DIGITE O TEXTO AQUI.");
alt4vouf.setForeground(new Color(153, 153, 153));
}
}//GEN-LAST:event_alt4voufFocusLost
private void alt5voufFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt5voufFocusLost
if(alt5vouf.getText().equals("")){
alt5vouf.setText("DIGITE O TEXTO AQUI.");
alt5vouf.setForeground(new Color(153, 153, 153));
}
}//GEN-LAST:event_alt5voufFocusLost
private void alt6voufFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt6voufFocusLost
if(alt6vouf.getText().equals("")){
alt6vouf.setText("DIGITE O TEXTO AQUI.");
alt6vouf.setForeground(new Color(153, 153, 153));
}
}//GEN-LAST:event_alt6voufFocusLost
private void alt7voufFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_alt7voufFocusLost
if(alt7vouf.getText().equals("")){
alt7vouf.setText("DIGITE O TEXTO AQUI.");
alt7vouf.setForeground(new Color(153, 153, 153));
}
}//GEN-LAST:event_alt7voufFocusLost
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InserirVouF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new InserirVouF().setVisible(true);
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private java.awt.Checkbox aleatorioCHK;
private javax.swing.JRadioButton alt1falso;
private javax.swing.JRadioButton alt1verdadeiro;
private javax.swing.JTextField alt1vouf;
private javax.swing.JRadioButton alt2falso;
private javax.swing.JRadioButton alt2verdadeiro;
private javax.swing.JTextField alt2vouf;
private javax.swing.JRadioButton alt3falso;
private javax.swing.JRadioButton alt3verdadeiro;
private javax.swing.JTextField alt3vouf;
private javax.swing.JRadioButton alt4falso;
private javax.swing.JRadioButton alt4verdadeiro;
private javax.swing.JTextField alt4vouf;
private javax.swing.JRadioButton alt5falso;
private javax.swing.JRadioButton alt5verdadeiro;
private javax.swing.JTextField alt5vouf;
private javax.swing.JRadioButton alt6falso;
private javax.swing.JRadioButton alt6verdadeiro;
private javax.swing.JTextField alt6vouf;
private javax.swing.JRadioButton alt7falso;
private javax.swing.JRadioButton alt7verdadeiro;
private javax.swing.JTextField alt7vouf;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.ButtonGroup buttonGroup4;
private javax.swing.ButtonGroup buttonGroup5;
private javax.swing.ButtonGroup buttonGroup6;
private javax.swing.ButtonGroup buttonGroup7;
private javax.swing.JButton desfazerImagem;
private javax.swing.JComboBox<String> dificuldadeVouF;
private javax.swing.JComboBox<String> disciplinaVouF;
private javax.swing.JTextField enunciadoVouF;
private javax.swing.JButton enviarVouF;
private javax.swing.JButton homeVouF;
private javax.swing.JButton imagemBTN;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel6;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JLabel labelImagem;
private javax.swing.JFileChooser seletorArq;
private javax.swing.JTextField temaVouF;
// End of variables declaration//GEN-END:variables
}
| mit |
om26er/autobahn-java | autobahn/src/main/java/io/crossbar/autobahn/wamp/types/Subscription.java | 1615 | ///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJava - http://crossbar.io/autobahn
//
// Copyright (c) Crossbar.io Technologies GmbH and contributors
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
package io.crossbar.autobahn.wamp.types;
import com.fasterxml.jackson.core.type.TypeReference;
import java.util.concurrent.CompletableFuture;
import io.crossbar.autobahn.wamp.Session;
public class Subscription {
public final long subscription;
public final String topic;
public final TypeReference resultTypeRef;
public final Class resultTypeClass;
public final Object handler;
public final Session session;
private boolean active = true;
public Subscription(long subscription, String topic, TypeReference resultTypeRef,
Class resultTypeClass, Object handler, Session session) {
this.subscription = subscription;
this.topic = topic;
this.resultTypeRef = resultTypeRef;
this.resultTypeClass = resultTypeClass;
this.handler = handler;
this.session = session;
}
public CompletableFuture<Integer> unsubscribe() {
return session.unsubscribe(this);
}
public void setInactive() {
if (active) {
active = false;
} else {
throw new IllegalStateException("Subscription already invactive");
}
}
public boolean isActive() {
return active;
}
}
| mit |
brunyuriy/quick-fix-scout | org.eclipse.jdt.ui_3.7.1.r371_v20110824-0800/src/org/eclipse/jdt/internal/ui/refactoring/nls/search/CompilationUnitEntry.java | 1253 | /*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.refactoring.nls.search;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.core.ICompilationUnit;
public class CompilationUnitEntry implements IAdaptable {
private final String fMessage;
private final ICompilationUnit fCompilationUnit;
public CompilationUnitEntry(String message, ICompilationUnit compilationUnit) {
fMessage= message;
fCompilationUnit= compilationUnit;
}
public String getMessage() {
return fMessage;
}
public ICompilationUnit getCompilationUnit() {
return fCompilationUnit;
}
public Object getAdapter(Class adapter) {
if (ICompilationUnit.class.equals(adapter))
return getCompilationUnit();
return null;
}
}
| mit |
patrickwestphal/mpj-express-mvn | src/main/java/mpi/GatherPackerInt.java | 2794 | /* This file generated automatically from template GatherPackerType.java.in. */
/*
The MIT License
Copyright (c) 2005 - 2008
1. Distributed Systems Group, University of Portsmouth (2005)
2. Community Grids Laboratory, Indiana University (2005)
3. Aamir Shafi (2005 - 2008)
4. Bryan Carpenter (2005 - 2008)
5. Mark Baker (2005 - 2008)
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.
*/
/*
* File : GatherPackerInt.java
* Author : Aamir Shafi, Bryan Carpenter
* Created : Fri Sep 10 12:22:15 BST 2004
* Revision : $Revision: 1.6 $
* Updated : $Date: 2005/07/29 14:03:09 $
*/
package mpi;
import mpjbuf.*;
public class GatherPackerInt extends GenericPacker {
public int [] displacements ;
public GatherPackerInt(int numEls, int [] displacements, int extent) {
super(extent, numEls) ;
this.displacements = displacements ;
}
public void pack(mpjbuf.Buffer mpjbuf, Object buf,
int offset) throws MPIException {
try {
mpjbuf.gather((int []) buf, size,
offset, displacements) ;
}
catch(Exception e) {
throw new MPIException(e);
}
}
public void unpack(mpjbuf.Buffer mpjbuf, Object buf,
int offset) throws MPIException {
try {
mpjbuf.scatter((int []) buf, size,
offset, displacements) ;
}
catch(Exception e) {
throw new MPIException(e);
}
}
public void unpackPartial(mpjbuf.Buffer mpjbuf, int length,
Object buf, int offset) throws MPIException {
try {
mpjbuf.scatter((int []) buf, size,
offset, displacements) ;
}
catch(Exception e) {
throw new MPIException(e);
}
}
}
| mit |
JBYoshi/SpongeCommon | src/main/java/org/spongepowered/common/mixin/realtime/mixin/MixinEntityXPOrb.java | 2795 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.mixin.realtime.mixin;
import net.minecraft.entity.item.EntityXPOrb;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.common.mixin.realtime.IMixinMinecraftServer;
@Mixin(EntityXPOrb.class)
public abstract class MixinEntityXPOrb {
private static final String ENTITY_XP_DELAY_PICKUP_FIELD = "Lnet/minecraft/entity/item/EntityXPOrb;delayBeforeCanPickup:I";
private static final String ENTITY_XP_AGE_FIELD = "Lnet/minecraft/entity/item/EntityXPOrb;xpOrbAge:I";
@Shadow public int delayBeforeCanPickup;
@Shadow public int xpOrbAge;
@Redirect(method = "onUpdate", at = @At(value = "FIELD", target = ENTITY_XP_DELAY_PICKUP_FIELD, opcode = Opcodes.PUTFIELD, ordinal = 0))
public void fixupPickupDelay(EntityXPOrb self, int modifier) {
int ticks = (int) ((IMixinMinecraftServer) self.getEntityWorld().getMinecraftServer()).getRealTimeTicks();
this.delayBeforeCanPickup = Math.max(0, this.delayBeforeCanPickup - ticks);
}
@Redirect(method = "onUpdate", at = @At(value = "FIELD", target = ENTITY_XP_AGE_FIELD, opcode = Opcodes.PUTFIELD, ordinal = 0))
public void fixupAge(EntityXPOrb self, int modifier) {
int ticks = (int) ((IMixinMinecraftServer) self.getEntityWorld().getMinecraftServer()).getRealTimeTicks();
this.xpOrbAge += ticks;
}
}
| mit |
csmith/DMDirc | api/src/main/java/com/dmdirc/events/ServerWallopsEvent.java | 2018 | /*
* Copyright (c) 2006-2017 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.events;
import com.dmdirc.interfaces.Connection;
import com.dmdirc.interfaces.User;
import java.time.LocalDateTime;
/**
* Fired when receiving a server wallops.
*/
public class ServerWallopsEvent extends ServerDisplayableEvent {
private final User user;
private final String message;
public ServerWallopsEvent(final LocalDateTime timestamp, final Connection connection,
final User user, final String message) {
super(timestamp, connection);
this.user = user;
this.message = message;
}
public ServerWallopsEvent(final Connection connection, final User user,
final String message) {
super(connection);
this.user = user;
this.message = message;
}
public User getUser() {
return user;
}
public String getMessage() {
return message;
}
}
| mit |
flamearrow/MonsterHunter4UDatabase | app/src/main/java/com/daviancorp/android/ui/detail/WishlistDetailActivity.java | 1707 | package com.daviancorp.android.ui.detail;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import com.daviancorp.android.data.database.DataManager;
import com.daviancorp.android.mh4udatabase.R;
import com.daviancorp.android.ui.adapter.WishlistDetailPagerAdapter;
import com.daviancorp.android.ui.general.GenericTabActivity;
import com.daviancorp.android.ui.list.adapter.MenuSection;
public class WishlistDetailActivity extends GenericTabActivity {
/**
* A key for passing a wishlist ID as a long
*/
public static final String EXTRA_WISHLIST_ID =
"com.daviancorp.android.android.ui.detail.wishlist_id";
private ViewPager viewPager;
private WishlistDetailPagerAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long id = getIntent().getLongExtra(EXTRA_WISHLIST_ID, -1);
setTitle(DataManager.get(getApplicationContext()).getWishlist(id).getName());
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new WishlistDetailPagerAdapter(getSupportFragmentManager(), id);
viewPager.setAdapter(mAdapter);
mSlidingTabLayout.setViewPager(viewPager);
}
@Override
protected MenuSection getSelectedSection() {
return MenuSection.WISH_LISTS;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// MenuInflater inflater = getMenuInflater();
// inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public void onPause() {
super.onPause();
}
}
| mit |
the100rabh/AntennaPod | core/src/main/java/de/danoeh/antennapod/core/util/NetworkUtils.java | 5721 | package de.danoeh.antennapod.core.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import de.danoeh.antennapod.core.feed.FeedMedia;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.service.download.AntennapodHttpClient;
import de.danoeh.antennapod.core.storage.DBWriter;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class NetworkUtils {
private static final String TAG = NetworkUtils.class.getSimpleName();
private static Context context;
public static void init(Context context) {
NetworkUtils.context = context;
}
/**
* Returns true if the device is connected to Wi-Fi and the Wi-Fi filter for
* automatic downloads is disabled or the device is connected to a Wi-Fi
* network that is on the 'selected networks' list of the Wi-Fi filter for
* automatic downloads and false otherwise.
* */
public static boolean autodownloadNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
Log.d(TAG, "Device is connected to Wi-Fi");
if (networkInfo.isConnected()) {
if (!UserPreferences.isEnableAutodownloadWifiFilter()) {
Log.d(TAG, "Auto-dl filter is disabled");
return true;
} else {
WifiManager wm = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wm.getConnectionInfo();
List<String> selectedNetworks = Arrays
.asList(UserPreferences
.getAutodownloadSelectedNetworks());
if (selectedNetworks.contains(Integer.toString(wifiInfo
.getNetworkId()))) {
Log.d(TAG, "Current network is on the selected networks list");
return true;
}
}
}
}
}
Log.d(TAG, "Network for auto-dl is not available");
return false;
}
public static boolean networkAvailable() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return info != null && info.isConnected();
}
public static boolean isDownloadAllowed() {
return UserPreferences.isAllowMobileUpdate() || NetworkUtils.connectedToWifi();
}
public static boolean connectedToWifi() {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi.isConnected();
}
public static Observable<Long> getFeedMediaSizeObservable(FeedMedia media) {
return Observable.create(new Observable.OnSubscribe<Long>() {
@Override
public void call(Subscriber<? super Long> subscriber) {
if (false == NetworkUtils.isDownloadAllowed()) {
subscriber.onNext(0L);
subscriber.onCompleted();
return;
}
long size = Integer.MIN_VALUE;
if (media.isDownloaded()) {
File mediaFile = new File(media.getLocalMediaUrl());
if (mediaFile.exists()) {
size = mediaFile.length();
}
} else if (false == media.checkedOnSizeButUnknown()) {
// only query the network if we haven't already checked
OkHttpClient client = AntennapodHttpClient.getHttpClient();
Request.Builder httpReq = new Request.Builder()
.url(media.getDownload_url())
.header("Accept-Encoding", "identity")
.head();
try {
Response response = client.newCall(httpReq.build()).execute();
if (response.isSuccessful()) {
String contentLength = response.header("Content-Length");
try {
size = Integer.parseInt(contentLength);
} catch (NumberFormatException e) {
Log.e(TAG, Log.getStackTraceString(e));
}
}
} catch (IOException e) {
subscriber.onNext(0L);
subscriber.onCompleted();
Log.e(TAG, Log.getStackTraceString(e));
return; // better luck next time
}
}
Log.d(TAG, "new size: " + size);
if (size <= 0) {
// they didn't tell us the size, but we don't want to keep querying on it
media.setCheckedOnSizeButUnknown();
} else {
media.setSize(size);
}
subscriber.onNext(size);
subscriber.onCompleted();
DBWriter.setFeedMedia(context, media);
}
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
}
}
| mit |
jenkinsci/scm-sync-configuration-plugin | src/test/java/hudson/plugins/scm_sync_configuration/repository/InitRepositoryGitTest.java | 254 | package hudson.plugins.scm_sync_configuration.repository;
import hudson.plugins.test.utils.scms.ScmUnderTestGit;
public class InitRepositoryGitTest extends InitRepositoryTest {
public InitRepositoryGitTest() {
super(new ScmUnderTestGit());
}
}
| mit |
drbgfc/mdht | hl7/plugins/org.openhealthtools.mdht.emf.hl7.mif2/src/org/openhealthtools/mdht/emf/hl7/mif2/ApprovalInfo.java | 12469 | /*******************************************************************************
* Copyright (c) 2006, 2009 David A Carlson
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.emf.hl7.mif2;
import java.math.BigInteger;
import javax.xml.datatype.XMLGregorianCalendar;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Approval Info</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* Indicates the approval status of the artifact(s).
* UML: Part of a complex tag value
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getBallotSubmission <em>Ballot Submission</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getApprovalDate <em>Approval Date</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getApprovalStatus <em>Approval Status</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getApprovingOrganization <em>Approving Organization</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getBallotOccurrence <em>Ballot Occurrence</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getWithdrawalDate <em>Withdrawal Date</em>}</li>
* </ul>
* </p>
*
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getApprovalInfo()
* @model extendedMetaData="name='ApprovalInfo' kind='elementOnly'"
* @generated
*/
public interface ApprovalInfo extends EObject {
/**
* Returns the value of the '<em><b>Ballot Submission</b></em>' containment reference list.
* The list contents are of type {@link org.openhealthtools.mdht.emf.hl7.mif2.BallotSubmission}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* A response submitted as part of the ballot
* UML: Part of a complex tag value
* <!-- end-model-doc -->
* @return the value of the '<em>Ballot Submission</em>' containment reference list.
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getApprovalInfo_BallotSubmission()
* @model containment="true"
* extendedMetaData="kind='element' name='ballotSubmission' namespace='##targetNamespace'"
* @generated
*/
EList<BallotSubmission> getBallotSubmission();
/**
* Returns the value of the '<em><b>Approval Date</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Indicates the date of the intended ballot (for material with a ballotStatus identifying itself as a ballot), or the date on which the material was successfully balloted (for material with a ballotStatus identifying itself as a Standard) or the date the approval status was changed (for non-balloted artifacts).
* UML: Part of a complex tag value
* DublinCore: for a passed ballot, maps to 'dateAccepted'
* <!-- end-model-doc -->
* @return the value of the '<em>Approval Date</em>' attribute.
* @see #setApprovalDate(XMLGregorianCalendar)
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getApprovalInfo_ApprovalDate()
* @model dataType="org.eclipse.emf.ecore.xml.type.Date"
* extendedMetaData="kind='attribute' name='approvalDate'"
* @generated
*/
XMLGregorianCalendar getApprovalDate();
/**
* Sets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getApprovalDate <em>Approval Date</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Approval Date</em>' attribute.
* @see #getApprovalDate()
* @generated
*/
void setApprovalDate(XMLGregorianCalendar value);
/**
* Returns the value of the '<em><b>Approval Status</b></em>' attribute.
* The literals are from the enumeration {@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalStatusKind}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Identifies how far along in the ballot process this artifact has progressed.
* UML: Part of a complex tag value
* <!-- end-model-doc -->
* @return the value of the '<em>Approval Status</em>' attribute.
* @see org.openhealthtools.mdht.emf.hl7.mif2.ApprovalStatusKind
* @see #isSetApprovalStatus()
* @see #unsetApprovalStatus()
* @see #setApprovalStatus(ApprovalStatusKind)
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getApprovalInfo_ApprovalStatus()
* @model unsettable="true" required="true"
* extendedMetaData="kind='attribute' name='approvalStatus'"
* @generated
*/
ApprovalStatusKind getApprovalStatus();
/**
* Sets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getApprovalStatus <em>Approval Status</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Approval Status</em>' attribute.
* @see org.openhealthtools.mdht.emf.hl7.mif2.ApprovalStatusKind
* @see #isSetApprovalStatus()
* @see #unsetApprovalStatus()
* @see #getApprovalStatus()
* @generated
*/
void setApprovalStatus(ApprovalStatusKind value);
/**
* Unsets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getApprovalStatus <em>Approval Status</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetApprovalStatus()
* @see #getApprovalStatus()
* @see #setApprovalStatus(ApprovalStatusKind)
* @generated
*/
void unsetApprovalStatus();
/**
* Returns whether the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getApprovalStatus <em>Approval Status</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Approval Status</em>' attribute is set.
* @see #unsetApprovalStatus()
* @see #getApprovalStatus()
* @see #setApprovalStatus(ApprovalStatusKind)
* @generated
*/
boolean isSetApprovalStatus();
/**
* Returns the value of the '<em><b>Approving Organization</b></em>' attribute.
* The default value is <code>"HL7"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Identifies the organization which has taken responsibility for balloting, endorsing or otherwise approving the content and the status for the content.
* UML: Part of a complex tag value
* <!-- end-model-doc -->
* @return the value of the '<em>Approving Organization</em>' attribute.
* @see #isSetApprovingOrganization()
* @see #unsetApprovingOrganization()
* @see #setApprovingOrganization(String)
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getApprovalInfo_ApprovingOrganization()
* @model default="HL7" unsettable="true" dataType="org.openhealthtools.mdht.emf.hl7.mif2.ShortDescriptiveName"
* extendedMetaData="kind='attribute' name='approvingOrganization'"
* @generated
*/
String getApprovingOrganization();
/**
* Sets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getApprovingOrganization <em>Approving Organization</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Approving Organization</em>' attribute.
* @see #isSetApprovingOrganization()
* @see #unsetApprovingOrganization()
* @see #getApprovingOrganization()
* @generated
*/
void setApprovingOrganization(String value);
/**
* Unsets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getApprovingOrganization <em>Approving Organization</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetApprovingOrganization()
* @see #getApprovingOrganization()
* @see #setApprovingOrganization(String)
* @generated
*/
void unsetApprovingOrganization();
/**
* Returns whether the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getApprovingOrganization <em>Approving Organization</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Approving Organization</em>' attribute is set.
* @see #unsetApprovingOrganization()
* @see #getApprovingOrganization()
* @see #setApprovingOrganization(String)
* @generated
*/
boolean isSetApprovingOrganization();
/**
* Returns the value of the '<em><b>Ballot Occurrence</b></em>' attribute.
* The default value is <code>"1"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Identifies the repetition number at the identified ballot level. (E.g. second time at committee level ballot.)
* UML: Part of a complex tag value
* <!-- end-model-doc -->
* @return the value of the '<em>Ballot Occurrence</em>' attribute.
* @see #isSetBallotOccurrence()
* @see #unsetBallotOccurrence()
* @see #setBallotOccurrence(BigInteger)
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getApprovalInfo_BallotOccurrence()
* @model default="1" unsettable="true" dataType="org.openhealthtools.mdht.emf.hl7.mif2.SmallPositiveInteger"
* extendedMetaData="kind='attribute' name='ballotOccurrence'"
* @generated
*/
BigInteger getBallotOccurrence();
/**
* Sets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getBallotOccurrence <em>Ballot Occurrence</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Ballot Occurrence</em>' attribute.
* @see #isSetBallotOccurrence()
* @see #unsetBallotOccurrence()
* @see #getBallotOccurrence()
* @generated
*/
void setBallotOccurrence(BigInteger value);
/**
* Unsets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getBallotOccurrence <em>Ballot Occurrence</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetBallotOccurrence()
* @see #getBallotOccurrence()
* @see #setBallotOccurrence(BigInteger)
* @generated
*/
void unsetBallotOccurrence();
/**
* Returns whether the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getBallotOccurrence <em>Ballot Occurrence</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Ballot Occurrence</em>' attribute is set.
* @see #unsetBallotOccurrence()
* @see #getBallotOccurrence()
* @see #setBallotOccurrence(BigInteger)
* @generated
*/
boolean isSetBallotOccurrence();
/**
* Returns the value of the '<em><b>Withdrawal Date</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Indicates the the item was or is planned to be officially withdrawn as a standard. For DSTUs, this is the intended sunset date for the DSTU specification.
* UML: Part of a complex tag value
* DublinCore: indicates the end date of 'valid'
* <!-- end-model-doc -->
* @return the value of the '<em>Withdrawal Date</em>' attribute.
* @see #setWithdrawalDate(XMLGregorianCalendar)
* @see org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package#getApprovalInfo_WithdrawalDate()
* @model dataType="org.eclipse.emf.ecore.xml.type.Date"
* extendedMetaData="kind='attribute' name='withdrawalDate'"
* @generated
*/
XMLGregorianCalendar getWithdrawalDate();
/**
* Sets the value of the '{@link org.openhealthtools.mdht.emf.hl7.mif2.ApprovalInfo#getWithdrawalDate <em>Withdrawal Date</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Withdrawal Date</em>' attribute.
* @see #getWithdrawalDate()
* @generated
*/
void setWithdrawalDate(XMLGregorianCalendar value);
} // ApprovalInfo
| epl-1.0 |
akervern/che | plugins/plugin-java/che-plugin-java-ext-lang-server/src/test/resources/RenameMethodInInterface/test11/in/A.java | 112 | //renaming I.m to k
package p;
interface I{
void m();
}
interface I2{
void m();
}
interface I3 extends I, I2{
}
| epl-1.0 |
ControlSystemStudio/cs-studio | thirdparty/plugins/org.eclipse.nebula.widgets.grid/src/org/eclipse/nebula/widgets/grid/internal/ToggleRenderer.java | 1972 | /*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* chris.gross@us.ibm.com - initial API and implementation
*******************************************************************************/
package org.eclipse.nebula.widgets.grid.internal;
import org.eclipse.nebula.widgets.grid.AbstractRenderer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
/**
* The renderer for tree item plus/minus expand/collapse toggle.
*
* @author chris.gross@us.ibm.com
* @since 2.0.0
*/
public class ToggleRenderer extends AbstractRenderer
{
/**
* Default constructor.
*/
public ToggleRenderer()
{
this.setSize(9, 9);
}
/**
* {@inheritDoc}
*/
public void paint(GC gc, Object value)
{
gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
gc.fillRectangle(getBounds());
gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW));
gc.drawRectangle(getBounds().x, getBounds().y, getBounds().width - 1,
getBounds().height - 1);
gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_FOREGROUND));
gc.drawLine(getBounds().x + 2, getBounds().y + 4, getBounds().x + 6, getBounds().y + 4);
if (!isExpanded())
{
gc.drawLine(getBounds().x + 4, getBounds().y + 2, getBounds().x + 4, getBounds().y + 6);
}
}
/**
* {@inheritDoc}
*/
public Point computeSize(GC gc, int wHint, int hHint, Object value)
{
return new Point(9, 9);
}
}
| epl-1.0 |
snjeza/che | wsagent/che-core-git-impl-jgit/src/main/java/org/eclipse/che/git/impl/jgit/JGitConnection.java | 89242 | /*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
* SAP - implementation
*******************************************************************************/
package org.eclipse.che.git.impl.jgit;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.eclipse.che.api.core.ErrorCodes;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.api.core.UnauthorizedException;
import org.eclipse.che.api.core.util.LineConsumer;
import org.eclipse.che.api.core.util.LineConsumerFactory;
import org.eclipse.che.api.git.Config;
import org.eclipse.che.api.git.CredentialsLoader;
import org.eclipse.che.api.git.DiffPage;
import org.eclipse.che.api.git.GitConnection;
import org.eclipse.che.api.git.exception.GitException;
import org.eclipse.che.api.git.exception.GitConflictException;
import org.eclipse.che.api.git.exception.GitRefAlreadyExistsException;
import org.eclipse.che.api.git.exception.GitRefNotFoundException;
import org.eclipse.che.api.git.exception.GitInvalidRefNameException;
import org.eclipse.che.api.git.GitUrlUtils;
import org.eclipse.che.api.git.GitUserResolver;
import org.eclipse.che.api.git.LogPage;
import org.eclipse.che.api.git.UserCredential;
import org.eclipse.che.api.git.params.AddParams;
import org.eclipse.che.api.git.params.LsFilesParams;
import org.eclipse.che.api.git.shared.BranchListMode;
import org.eclipse.che.api.git.params.CheckoutParams;
import org.eclipse.che.api.git.params.CloneParams;
import org.eclipse.che.api.git.params.CommitParams;
import org.eclipse.che.api.git.params.DiffParams;
import org.eclipse.che.api.git.params.FetchParams;
import org.eclipse.che.api.git.params.LogParams;
import org.eclipse.che.api.git.params.PullParams;
import org.eclipse.che.api.git.params.PushParams;
import org.eclipse.che.api.git.params.RemoteAddParams;
import org.eclipse.che.api.git.params.RemoteUpdateParams;
import org.eclipse.che.api.git.params.ResetParams;
import org.eclipse.che.api.git.params.RmParams;
import org.eclipse.che.api.git.params.TagCreateParams;
import org.eclipse.che.api.git.shared.AddRequest;
import org.eclipse.che.api.git.shared.Branch;
import org.eclipse.che.api.git.shared.DiffCommitFile;
import org.eclipse.che.api.git.shared.GitUser;
import org.eclipse.che.api.git.shared.MergeResult;
import org.eclipse.che.api.git.shared.ProviderInfo;
import org.eclipse.che.api.git.shared.PullResponse;
import org.eclipse.che.api.git.shared.PushResponse;
import org.eclipse.che.api.git.shared.RebaseResponse;
import org.eclipse.che.api.git.shared.RebaseResponse.RebaseStatus;
import org.eclipse.che.api.git.shared.Remote;
import org.eclipse.che.api.git.shared.RemoteReference;
import org.eclipse.che.api.git.shared.Revision;
import org.eclipse.che.api.git.shared.ShowFileContentResponse;
import org.eclipse.che.api.git.shared.Status;
import org.eclipse.che.api.git.shared.StatusFormat;
import org.eclipse.che.api.git.shared.Tag;
import org.eclipse.che.commons.annotation.Nullable;
import org.eclipse.che.plugin.ssh.key.script.SshKeyProvider;
import org.eclipse.che.commons.proxy.ProxyAuthenticator;
import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.CheckoutCommand;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.CommitCommand;
import org.eclipse.jgit.api.CreateBranchCommand;
import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode;
import org.eclipse.jgit.api.FetchCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ListBranchCommand;
import org.eclipse.jgit.api.ListBranchCommand.ListMode;
import org.eclipse.jgit.api.LogCommand;
import org.eclipse.jgit.api.LsRemoteCommand;
import org.eclipse.jgit.api.PushCommand;
import org.eclipse.jgit.api.RebaseCommand;
import org.eclipse.jgit.api.RebaseResult;
import org.eclipse.jgit.api.ResetCommand;
import org.eclipse.jgit.api.ResetCommand.ResetType;
import org.eclipse.jgit.api.RmCommand;
import org.eclipse.jgit.api.TagCommand;
import org.eclipse.jgit.api.TransportCommand;
import org.eclipse.jgit.api.errors.CheckoutConflictException;
import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
import org.eclipse.jgit.api.errors.InvalidRefNameException;
import org.eclipse.jgit.api.errors.RefNotFoundException;
import org.eclipse.jgit.api.errors.DetachedHeadException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.lib.BatchingProgressMonitor;
import org.eclipse.jgit.lib.ConfigConstants;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.RefUpdate.Result;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryCache;
import org.eclipse.jgit.lib.RepositoryState;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.merge.ResolveMerger;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevObject;
import org.eclipse.jgit.revwalk.RevTag;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.FetchResult;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.transport.PushResult;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.RemoteRefUpdate;
import org.eclipse.jgit.transport.SshSessionFactory;
import org.eclipse.jgit.transport.SshTransport;
import org.eclipse.jgit.transport.TrackingRefUpdate;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.treewalk.CanonicalTreeParser;
import org.eclipse.jgit.treewalk.EmptyTreeIterator;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
import org.eclipse.jgit.treewalk.filter.TreeFilter;
import org.eclipse.jgit.treewalk.filter.PathFilter;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.FileUtils;
import org.eclipse.jgit.util.io.NullOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.net.ssl.SSLHandshakeException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.attribute.PosixFilePermission;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;
import static java.lang.System.lineSeparator;
import static java.nio.file.attribute.PosixFilePermission.OWNER_READ;
import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.eclipse.che.api.git.shared.BranchListMode.LIST_ALL;
import static org.eclipse.che.api.git.shared.BranchListMode.LIST_LOCAL;
import static org.eclipse.che.api.git.shared.BranchListMode.LIST_REMOTE;
import static org.eclipse.che.api.git.shared.ProviderInfo.AUTHENTICATE_URL;
import static org.eclipse.che.api.git.shared.ProviderInfo.PROVIDER_NAME;
import static org.eclipse.che.dto.server.DtoFactory.newDto;
/**
* @author Andrey Parfonov
* @author Igor Vinokur
* @author Mykola Morhun
*/
class JGitConnection implements GitConnection {
private static final String REBASE_OPERATION_SKIP = "SKIP";
private static final String REBASE_OPERATION_CONTINUE = "CONTINUE";
private static final String REBASE_OPERATION_ABORT = "ABORT";
// Push Response Constants
private static final String BRANCH_REFSPEC_SEPERATOR = " -> ";
private static final String REFSPEC_COLON = ":";
private static final String KEY_COMMIT_MESSAGE = "Message";
private static final String KEY_RESULT = "Result";
private static final String KEY_REMOTENAME = "RemoteName";
private static final String KEY_LOCALNAME = "LocalName";
private static final String ERROR_UPDATE_REMOTE_NAME_MISSING = "Update operation failed, remote name is required.";
private static final String ERROR_UPDATE_REMOTE_REMOVE_INVALID_URL = "remoteUpdate: Ignore this error. Cannot remove invalid URL.";
private static final String ERROR_ADD_REMOTE_NAME_ALREADY_EXISTS = "Add Remote operation failed, remote name %s already exists.";
private static final String ERROR_ADD_REMOTE_NAME_MISSING = "Add operation failed, remote name is required.";
private static final String ERROR_ADD_REMOTE_URL_MISSING = "Add Remote operation failed, Remote url required.";
private static final String ERROR_PULL_MERGING = "Could not pull because the repository state is 'MERGING'.";
private static final String ERROR_PULL_HEAD_DETACHED = "Could not pull because HEAD is detached.";
private static final String ERROR_PULL_REF_MISSING = "Could not pull because remote ref is missing for branch %s.";
private static final String ERROR_PULL_AUTO_MERGE_FAILED = "Automatic merge failed; fix conflicts and then commit the result.";
private static final String ERROR_PULL_MERGE_CONFLICT_IN_FILES = "Could not pull because a merge conflict is detected in the files:";
private static final String ERROR_PULL_COMMIT_BEFORE_MERGE = "Could not pull. Commit your changes before merging.";
private static final String ERROR_CHECKOUT_BRANCH_NAME_EXISTS = "A branch named '%s' already exists.";
private static final String ERROR_CHECKOUT_CONFLICT = "Checkout operation failed, the following files would be " +
"overwritten by merge:";
private static final String ERROR_PUSH_CONFLICTS_PRESENT = "failed to push '%s' to '%s'. Try to merge " +
"remote changes using pull, and then push again.";
private static final String INFO_PUSH_IGNORED_UP_TO_DATE = "Everything up-to-date";
private static final String ERROR_AUTHENTICATION_REQUIRED = "Authentication is required but no CredentialsProvider has been registered";
private static final String ERROR_AUTHENTICATION_FAILED = "fatal: Authentication failed for '%s/'" + lineSeparator();
private static final String ERROR_TAG_DELETE = "Could not delete the tag %1$s. An error occurred: %2$s.";
private static final String ERROR_LOG_NO_HEAD_EXISTS = "No HEAD exists and no explicit starting revision was specified";
private static final String ERROR_INIT_FOLDER_MISSING = "The working folder %s does not exist.";
private static final String ERROR_NO_REMOTE_REPOSITORY = "No remote repository specified. Please, specify either a " +
"URL or a remote name from which new revisions should be " +
"fetched in request.";
private static final String MESSAGE_COMMIT_NOT_POSSIBLE = "Commit is not possible because repository state is '%s'";
private static final String MESSAGE_COMMIT_AMEND_NOT_POSSIBLE = "Amend is not possible because repository state is '%s'";
private static final String FILE_NAME_TOO_LONG_ERROR_PREFIX = "File name too long";
private static final Pattern GIT_URL_WITH_CREDENTIALS_PATTERN = Pattern.compile("https?://[^:]+:[^@]+@.*");
private static final Logger LOG = LoggerFactory.getLogger(JGitConnection.class);
private Git git;
private JGitConfigImpl config;
private LineConsumerFactory lineConsumerFactory;
private final CredentialsLoader credentialsLoader;
private final SshKeyProvider sshKeyProvider;
private final GitUserResolver userResolver;
private final Repository repository;
@Inject
JGitConnection(Repository repository, CredentialsLoader credentialsLoader, SshKeyProvider sshKeyProvider,
GitUserResolver userResolver) {
this.repository = repository;
this.credentialsLoader = credentialsLoader;
this.sshKeyProvider = sshKeyProvider;
this.userResolver = userResolver;
}
@Override
public void add(AddParams params) throws GitException {
AddCommand addCommand = getGit().add().setUpdate(params.isUpdate());
List<String> filePatterns = params.getFilePattern();
if (filePatterns.isEmpty()) {
filePatterns = AddRequest.DEFAULT_PATTERN;
}
filePatterns.forEach(addCommand::addFilepattern);
try {
addCommand.call();
addDeletedFilesToIndex(filePatterns);
} catch (GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
/** To add deleted files in index it is required to perform git rm on them */
private void addDeletedFilesToIndex(List<String> filePatterns) throws GitAPIException {
Set<String> deletedFiles = getGit().status().call().getMissing();
if (!deletedFiles.isEmpty()) {
RmCommand rmCommand = getGit().rm();
if (filePatterns.contains(".")) {
deletedFiles.forEach(rmCommand::addFilepattern);
} else {
filePatterns.forEach(filePattern -> deletedFiles.stream()
.filter(deletedFile -> deletedFile.startsWith(filePattern))
.forEach(rmCommand::addFilepattern));
}
rmCommand.call();
}
}
@Override
public void checkout(CheckoutParams params) throws GitException {
CheckoutCommand checkoutCommand = getGit().checkout();
String startPoint = params.getStartPoint();
String name = params.getName();
String trackBranch = params.getTrackBranch();
// checkout files?
List<String> files = params.getFiles();
boolean shouldCheckoutToFile = name != null && new File(getWorkingDir(), name).exists();
if (shouldCheckoutToFile || !files.isEmpty()) {
if (shouldCheckoutToFile) {
checkoutCommand.addPath(params.getName());
} else {
files.forEach(checkoutCommand::addPath);
}
} else {
// checkout branch
if (startPoint != null && trackBranch != null) {
throw new GitException("Start point and track branch can not be used together.");
}
if (params.isCreateNew() && name == null) {
throw new GitException("Branch name must be set when createNew equals to true.");
}
if (startPoint != null) {
checkoutCommand.setStartPoint(startPoint);
}
if (params.isCreateNew()) {
checkoutCommand.setCreateBranch(true);
checkoutCommand.setName(name);
} else if (name != null) {
checkoutCommand.setName(name);
List<String> localBranches = branchList(LIST_LOCAL).stream()
.map(Branch::getDisplayName)
.collect(Collectors.toList());
if (!localBranches.contains(name)) {
Optional<Branch> remoteBranch = branchList(LIST_REMOTE).stream()
.filter(branch -> branch.getName().contains(name))
.findFirst();
if (remoteBranch.isPresent()) {
checkoutCommand.setCreateBranch(true);
checkoutCommand.setStartPoint(remoteBranch.get().getName());
}
}
}
if (trackBranch != null) {
if (name == null) {
checkoutCommand.setName(cleanRemoteName(trackBranch));
}
checkoutCommand.setCreateBranch(true);
checkoutCommand.setStartPoint(trackBranch);
}
checkoutCommand.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
}
try {
checkoutCommand.call();
} catch (CheckoutConflictException exception) {
throw new GitConflictException(exception.getMessage(), exception.getConflictingPaths());
} catch (RefAlreadyExistsException exception) {
throw new GitRefAlreadyExistsException(exception.getMessage());
} catch (RefNotFoundException exception) {
throw new GitRefNotFoundException(exception.getMessage());
} catch (InvalidRefNameException exception) {
throw new GitInvalidRefNameException(exception.getMessage());
} catch (GitAPIException exception) {
if (exception.getMessage().endsWith("already exists")) {
throw new GitException(format(ERROR_CHECKOUT_BRANCH_NAME_EXISTS, name != null ? name : cleanRemoteName(trackBranch)));
}
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public Branch branchCreate(String name, String startPoint) throws GitException {
CreateBranchCommand createBranchCommand = getGit().branchCreate().setName(name);
if (startPoint != null) {
createBranchCommand.setStartPoint(startPoint);
}
try {
Ref brRef = createBranchCommand.call();
String refName = brRef.getName();
String displayName = Repository.shortenRefName(refName);
return newDto(Branch.class).withName(refName)
.withDisplayName(displayName)
.withActive(false)
.withRemote(false);
} catch (GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public void branchDelete(String name, boolean force) throws GitException {
try {
getGit().branchDelete()
.setBranchNames(name)
.setForce(force)
.call();
} catch (GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public void branchRename(String oldName, String newName) throws GitException {
try {
getGit().branchRename()
.setOldName(oldName)
.setNewName(newName)
.call();
} catch (GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public List<Branch> branchList(BranchListMode listMode) throws GitException {
ListBranchCommand listBranchCommand = getGit().branchList();
if (LIST_ALL == listMode || listMode == null) {
listBranchCommand.setListMode(ListMode.ALL);
} else if (LIST_REMOTE == listMode) {
listBranchCommand.setListMode(ListMode.REMOTE);
}
List<Ref> refs;
String currentRef;
try {
refs = listBranchCommand.call();
String headBranch = getRepository().getBranch();
Optional<Ref> currentTag = getGit().tagList().call().stream()
.filter(tag -> tag.getObjectId().getName().equals(headBranch))
.findFirst();
if (currentTag.isPresent()) {
currentRef = currentTag.get().getName();
} else {
currentRef = "refs/heads/" + headBranch;
}
} catch (GitAPIException | IOException exception) {
throw new GitException(exception.getMessage(), exception);
}
List<Branch> branches = new ArrayList<>();
for (Ref ref : refs) {
String refName = ref.getName();
boolean isCommitOrTag = Constants.HEAD.equals(refName);
String branchName = isCommitOrTag ? currentRef : refName;
String branchDisplayName;
if (isCommitOrTag) {
branchDisplayName = "(detached from " + Repository.shortenRefName(currentRef) + ")";
} else {
branchDisplayName = Repository.shortenRefName(refName);
}
Branch branch = newDto(Branch.class).withName(branchName)
.withActive(isCommitOrTag || refName.equals(currentRef))
.withDisplayName(branchDisplayName)
.withRemote(refName.startsWith("refs/remotes"));
branches.add(branch);
}
return branches;
}
public void clone(CloneParams params) throws GitException, UnauthorizedException {
String remoteUri = params.getRemoteUrl();
boolean removeIfFailed = false;
try {
if (params.getRemoteName() == null) {
params.setRemoteName(Constants.DEFAULT_REMOTE_NAME);
}
if (params.getWorkingDir() == null) {
params.setWorkingDir(repository.getWorkTree().getCanonicalPath());
}
// If clone fails and the .git folder didn't exist we want to remove it.
// We have to do this here because the clone command doesn't revert its own changes in case of failure.
removeIfFailed = !repository.getDirectory().exists();
CloneCommand cloneCommand = Git.cloneRepository()
.setDirectory(new File(params.getWorkingDir()))
.setRemote(params.getRemoteName())
.setCloneSubmodules(params.isRecursive())
.setURI(remoteUri);
if (params.getBranchesToFetch().isEmpty()) {
cloneCommand.setCloneAllBranches(true);
} else {
cloneCommand.setBranchesToClone(params.getBranchesToFetch());
}
LineConsumer lineConsumer = lineConsumerFactory.newLineConsumer();
cloneCommand.setProgressMonitor(new BatchingProgressMonitor() {
@Override
protected void onUpdate(String taskName, int workCurr) {
try {
lineConsumer.writeLine(taskName + ": " + workCurr + " completed");
} catch (IOException exception) {
LOG.error(exception.getMessage(), exception);
}
}
@Override
protected void onEndTask(String taskName, int workCurr) {
}
@Override
protected void onUpdate(String taskName, int workCurr, int workTotal, int percentDone) {
try {
lineConsumer.writeLine(taskName + ": " + workCurr + " of " + workTotal + " completed, " + percentDone + "% done");
} catch (IOException exception) {
LOG.error(exception.getMessage(), exception);
}
}
@Override
protected void onEndTask(String taskName, int workCurr, int workTotal, int percentDone) {
}
});
((Git)executeRemoteCommand(remoteUri, cloneCommand, params.getUsername(), params.getPassword())).close();
StoredConfig repositoryConfig = getRepository().getConfig();
GitUser gitUser = getUser();
if (gitUser != null) {
repositoryConfig.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_NAME, gitUser.getName());
repositoryConfig.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_EMAIL, gitUser.getEmail());
}
repositoryConfig.save();
} catch (IOException | GitAPIException exception) {
// Delete .git directory in case it was created
if (removeIfFailed) {
deleteRepositoryFolder();
}
//TODO remove this when JGit will support HTTP 301 redirects, https://bugs.eclipse.org/bugs/show_bug.cgi?id=465167
//try to clone repository by replacing http to https in the url if HTTP 301 redirect happened
if (exception.getMessage().contains(": 301 Moved Permanently")) {
remoteUri = "https" + remoteUri.substring(4);
try {
clone(params.withRemoteUrl(remoteUri));
} catch (UnauthorizedException | GitException e) {
throw new GitException("Failed to clone the repository", e);
}
return;
}
String message = generateExceptionMessage(exception);
throw new GitException(message, exception);
}
}
@Override
public Revision commit(CommitParams params) throws GitException {
try {
// Check repository state
RepositoryState repositoryState = repository.getRepositoryState();
if (!repositoryState.canCommit()) {
throw new GitException(format(MESSAGE_COMMIT_NOT_POSSIBLE, repositoryState.getDescription()));
}
if (params.isAmend() && !repositoryState.canAmend()) {
throw new GitException(format(MESSAGE_COMMIT_AMEND_NOT_POSSIBLE, repositoryState.getDescription()));
}
// Check committer
GitUser committer = getUser();
if (committer == null) {
throw new GitException("Committer can't be null");
}
String committerName = committer.getName();
String committerEmail = committer.getEmail();
if (committerName == null || committerEmail == null) {
throw new GitException("Git user name and (or) email wasn't set", ErrorCodes.NO_COMMITTER_NAME_OR_EMAIL_DEFINED);
}
// Check commit message
String message = params.getMessage();
if (message == null) {
throw new GitException("Message wasn't set");
}
Status status = status(StatusFormat.SHORT);
List<String> specified = params.getFiles();
List<String> staged = new ArrayList<>();
staged.addAll(status.getAdded());
staged.addAll(status.getChanged());
staged.addAll(status.getRemoved());
List<String> changed = new ArrayList<>(staged);
changed.addAll(status.getModified());
changed.addAll(status.getMissing());
List<String> specifiedStaged = specified.stream()
.filter(path -> staged.stream().anyMatch(s -> s.startsWith(path)))
.collect(Collectors.toList());
List<String> specifiedChanged = specified.stream()
.filter(path -> changed.stream().anyMatch(c -> c.startsWith(path)))
.collect(Collectors.toList());
// Check that there are changes present for commit, if 'isAmend' is disabled
if (!params.isAmend()) {
// Check that there are staged changes present for commit, or any changes if 'isAll' is enabled
if (status.isClean()) {
throw new GitException("Nothing to commit, working directory clean");
} else if (!params.isAll() && (specified.isEmpty() ? staged.isEmpty() : specifiedStaged.isEmpty())) {
throw new GitException("No changes added to commit");
}
} else {
/*
By default Jgit doesn't allow to commit not changed specified paths. According to setAllowEmpty method documentation,
setting this flag to true must allow such commit, but it won't because Jgit has a bug:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=510685. As a workaround, specified paths of the commit command will contain
only changed and specified paths. If other changes are present, but the list of changed and specified paths is empty,
throw exception to prevent committing other paths. TODO Remove this check when the bug will be fixed.
*/
if (!specified.isEmpty() && !(params.isAll() ? changed.isEmpty() : staged.isEmpty()) && specifiedChanged.isEmpty()) {
throw new GitException(format("Changes are present but not changed path%s specified for commit.",
specified.size() > 1 ? "s were" : " was"));
}
}
// TODO add 'setAllowEmpty(params.isAmend())' when https://bugs.eclipse.org/bugs/show_bug.cgi?id=510685 will be fixed
CommitCommand commitCommand = getGit().commit()
.setCommitter(committerName, committerEmail)
.setAuthor(committerName, committerEmail)
.setMessage(message)
.setAll(params.isAll())
.setAmend(params.isAmend());
if (!params.isAll()) {
// TODO change to 'specified.forEach(commitCommand::setOnly)' when https://bugs.eclipse.org/bugs/show_bug.cgi?id=510685 will be fixed. See description above.
specifiedChanged.forEach(commitCommand::setOnly);
}
// Check if repository is configured with Gerrit Support
String gerritSupportConfigValue = repository.getConfig().getString(ConfigConstants.CONFIG_GERRIT_SECTION, null,
ConfigConstants.CONFIG_KEY_CREATECHANGEID);
boolean isGerritSupportConfigured = gerritSupportConfigValue != null ? Boolean.valueOf(gerritSupportConfigValue) : false;
commitCommand.setInsertChangeId(isGerritSupportConfigured);
RevCommit result = commitCommand.call();
GitUser gitUser = newDto(GitUser.class).withName(committerName).withEmail(committerEmail);
return newDto(Revision.class).withBranch(getCurrentBranch())
.withId(result.getId().getName()).withMessage(result.getFullMessage())
.withCommitTime(MILLISECONDS.convert(result.getCommitTime(), SECONDS))
.withCommitter(gitUser);
} catch (GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public DiffPage diff(DiffParams params) throws GitException {
return new JGitDiffPage(params, repository);
}
@Override
public boolean isInsideWorkTree() throws GitException {
return RepositoryCache.FileKey.isGitRepository(getRepository().getDirectory(), FS.DETECTED);
}
@Override
public ShowFileContentResponse showFileContent(String file, String version) throws GitException {
String content;
ObjectId revision;
try {
revision = getRepository().resolve(version);
try (RevWalk revWalk = new RevWalk(getRepository())) {
RevCommit revCommit = revWalk.parseCommit(revision);
RevTree tree = revCommit.getTree();
try (TreeWalk treeWalk = new TreeWalk(getRepository())) {
treeWalk.addTree(tree);
treeWalk.setRecursive(true);
treeWalk.setFilter(PathFilter.create(file));
if (!treeWalk.next()) {
throw new GitException("fatal: Path '" + file + "' does not exist in '" + version + "'" + lineSeparator());
}
ObjectId objectId = treeWalk.getObjectId(0);
ObjectLoader loader = repository.open(objectId);
content = new String(loader.getBytes());
}
}
} catch (IOException exception) {
throw new GitException(exception.getMessage());
}
return newDto(ShowFileContentResponse.class).withContent(content);
}
@Override
public void fetch(FetchParams params) throws GitException, UnauthorizedException {
String remoteName = params.getRemote();
String remoteUri;
try {
List<RefSpec> fetchRefSpecs;
List<String> refSpec = params.getRefSpec();
if (!refSpec.isEmpty()) {
fetchRefSpecs = new ArrayList<>(refSpec.size());
for (String refSpecItem : refSpec) {
RefSpec fetchRefSpec = (refSpecItem.indexOf(':') < 0) //
? new RefSpec(Constants.R_HEADS + refSpecItem + ":") //
: new RefSpec(refSpecItem);
fetchRefSpecs.add(fetchRefSpec);
}
} else {
fetchRefSpecs = Collections.emptyList();
}
FetchCommand fetchCommand = getGit().fetch();
// If this an unknown remote with no refspecs given, put HEAD
// (otherwise JGit fails)
if (remoteName != null && refSpec.isEmpty()) {
boolean found = false;
List<Remote> configRemotes = remoteList(null, false);
for (Remote configRemote : configRemotes) {
if (remoteName.equals(configRemote.getName())) {
found = true;
break;
}
}
if (!found) {
fetchRefSpecs = Collections.singletonList(new RefSpec(Constants.HEAD + ":" + Constants.FETCH_HEAD));
}
}
if (remoteName == null) {
remoteName = Constants.DEFAULT_REMOTE_NAME;
}
fetchCommand.setRemote(remoteName);
remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName,
ConfigConstants.CONFIG_KEY_URL);
fetchCommand.setRefSpecs(fetchRefSpecs);
int timeout = params.getTimeout();
if (timeout > 0) {
fetchCommand.setTimeout(timeout);
}
fetchCommand.setRemoveDeletedRefs(params.isRemoveDeletedRefs());
executeRemoteCommand(remoteUri, fetchCommand, params.getUsername(), params.getPassword());
} catch (GitException | GitAPIException exception) {
String errorMessage;
if (exception.getMessage().contains("Invalid remote: ")) {
errorMessage = ERROR_NO_REMOTE_REPOSITORY;
} else if ("Nothing to fetch.".equals(exception.getMessage())) {
return;
} else {
errorMessage = generateExceptionMessage(exception);
}
throw new GitException(errorMessage, exception);
}
}
@Override
public void init(boolean isBare) throws GitException {
File workDir = repository.getWorkTree();
if (!workDir.exists()) {
throw new GitException(format(ERROR_INIT_FOLDER_MISSING, workDir));
}
// If create fails and the .git folder didn't exist we want to remove it.
// We have to do this here because the create command doesn't revert its own changes in case of failure.
boolean removeIfFailed = !repository.getDirectory().exists();
try {
repository.create(isBare);
} catch (IOException exception) {
if (removeIfFailed) {
deleteRepositoryFolder();
}
throw new GitException(exception.getMessage(), exception);
}
}
/** @see org.eclipse.che.api.git.GitConnection#log(LogParams) */
@Override
public LogPage log(LogParams params) throws GitException {
LogCommand logCommand = getGit().log();
try {
setRevisionRange(logCommand, params);
logCommand.setSkip(params.getSkip());
logCommand.setMaxCount(params.getMaxCount());
List<String> fileFilter = params.getFileFilter();
if (fileFilter != null) {
fileFilter.forEach(logCommand::addPath);
}
String filePath = params.getFilePath();
if (!isNullOrEmpty(filePath)) {
logCommand.addPath(filePath);
}
Iterator<RevCommit> revIterator = logCommand.call().iterator();
List<Revision> commits = new ArrayList<>();
while (revIterator.hasNext()) {
RevCommit commit = revIterator.next();
Revision revision = getRevision(commit, filePath);
commits.add(revision);
}
return new LogPage(commits);
} catch (GitAPIException | IOException exception) {
String errorMessage = exception.getMessage();
if (ERROR_LOG_NO_HEAD_EXISTS.equals(errorMessage)) {
throw new GitException(errorMessage, ErrorCodes.INIT_COMMIT_WAS_NOT_PERFORMED);
} else {
LOG.error("Failed to retrieve log. ", exception);
throw new GitException(exception);
}
}
}
private Revision getRevision(RevCommit commit, String filePath) throws GitAPIException, IOException {
List<String> commitParentsList = Stream.of(commit.getParents())
.map(RevCommit::getName)
.collect(Collectors.toList());
return newDto(Revision.class).withId(commit.getId().getName())
.withMessage(commit.getFullMessage())
.withCommitTime((long)commit.getCommitTime() * 1000)
.withCommitter(getCommitCommitter(commit))
.withAuthor(getCommitAuthor(commit))
.withBranches(getBranchesOfCommit(commit, ListMode.ALL))
.withCommitParent(commitParentsList)
.withDiffCommitFile(getCommitDiffFiles(commit, filePath));
}
private GitUser getCommitCommitter(RevCommit commit) {
PersonIdent committerIdentity = commit.getCommitterIdent();
return newDto(GitUser.class).withName(committerIdentity.getName())
.withEmail(committerIdentity.getEmailAddress());
}
private GitUser getCommitAuthor(RevCommit commit) {
PersonIdent authorIdentity = commit.getAuthorIdent();
return newDto(GitUser.class).withName(authorIdentity.getName())
.withEmail(authorIdentity.getEmailAddress());
}
private List<Branch> getBranchesOfCommit(RevCommit commit, ListMode mode) throws GitAPIException {
List<Ref> branches = getGit().branchList()
.setListMode(mode)
.setContains(commit.getName())
.call();
return branches.stream()
.map(branch -> newDto(Branch.class).withName(branch.getName()))
.collect(Collectors.toList());
}
private List<DiffCommitFile> getCommitDiffFiles(RevCommit revCommit, String pattern) throws IOException {
List<DiffEntry> diffs;
TreeFilter filter = null;
if (!isNullOrEmpty(pattern)) {
filter = AndTreeFilter.create(PathFilterGroup.createFromStrings(Collections.singleton(pattern)), TreeFilter.ANY_DIFF);
}
List<DiffCommitFile> commitFilesList = new ArrayList<>();
try (TreeWalk tw = new TreeWalk(repository)) {
tw.setRecursive(true);
// get the current commit parent in order to compare it with the current commit
// and to get the list of DiffEntry.
if (revCommit.getParentCount() > 0) {
RevCommit parent = parseCommit(revCommit.getParent(0));
tw.reset(parent.getTree(), revCommit.getTree());
if (filter != null) {
tw.setFilter(filter);
} else {
tw.setFilter(TreeFilter.ANY_DIFF);
}
diffs = DiffEntry.scan(tw);
} else {
// If the current commit has no parents (which means it is the initial commit),
// then create an empty tree and compare it to the current commit to get the
// list of DiffEntry.
try (RevWalk rw = new RevWalk(repository);
DiffFormatter diffFormat = new DiffFormatter(NullOutputStream.INSTANCE)) {
diffFormat.setRepository(repository);
if (filter != null) {
diffFormat.setPathFilter(filter);
}
diffs = diffFormat.scan(new EmptyTreeIterator(),
new CanonicalTreeParser(null, rw.getObjectReader(), revCommit.getTree()));
}
}
}
if (diffs != null) {
commitFilesList.addAll(diffs.stream().map(diff -> newDto(DiffCommitFile.class).withOldPath(diff.getOldPath())
.withNewPath(diff.getNewPath())
.withChangeType(diff.getChangeType().name()))
.collect(Collectors.toList()));
}
return commitFilesList;
}
private RevCommit parseCommit(RevCommit revCommit) {
try (RevWalk rw = new RevWalk(repository)) {
return rw.parseCommit(revCommit);
} catch (IOException exception) {
LOG.error("Failed to parse commit. ", exception);
return revCommit;
}
}
private void setRevisionRange(LogCommand logCommand, LogParams params) throws IOException {
if (params != null && logCommand != null) {
String revisionRangeSince = params.getRevisionRangeSince();
String revisionRangeUntil = params.getRevisionRangeUntil();
if (revisionRangeSince != null && revisionRangeUntil != null) {
ObjectId since = repository.resolve(revisionRangeSince);
ObjectId until = repository.resolve(revisionRangeUntil);
logCommand.addRange(since, until);
}
}
}
@Override
public List<GitUser> getCommiters() throws GitException {
List<GitUser> gitUsers = new ArrayList<>();
try {
LogCommand logCommand = getGit().log();
for (RevCommit commit : logCommand.call()) {
PersonIdent committerIdentity = commit.getCommitterIdent();
GitUser gitUser = newDto(GitUser.class).withName(committerIdentity.getName())
.withEmail(committerIdentity.getEmailAddress());
if (!gitUsers.contains(gitUser)) {
gitUsers.add(gitUser);
}
}
} catch (GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
return gitUsers;
}
@Override
public MergeResult merge(String commit) throws GitException {
org.eclipse.jgit.api.MergeResult jGitMergeResult;
MergeResult.MergeStatus status;
try {
Ref ref = repository.findRef(commit);
if (ref == null) {
throw new GitException("Invalid reference to commit for merge " + commit);
}
// Shorten local branch names by removing '/refs/heads/' from the beginning
String name = ref.getName();
if (name.startsWith(Constants.R_HEADS)) {
name = name.substring(Constants.R_HEADS.length());
}
jGitMergeResult = getGit().merge().include(name, ref.getObjectId()).call();
} catch (CheckoutConflictException exception) {
jGitMergeResult = new org.eclipse.jgit.api.MergeResult(exception.getConflictingPaths());
} catch (IOException | GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
switch (jGitMergeResult.getMergeStatus()) {
case ALREADY_UP_TO_DATE:
status = MergeResult.MergeStatus.ALREADY_UP_TO_DATE;
break;
case CONFLICTING:
status = MergeResult.MergeStatus.CONFLICTING;
break;
case FAILED:
status = MergeResult.MergeStatus.FAILED;
break;
case FAST_FORWARD:
status = MergeResult.MergeStatus.FAST_FORWARD;
break;
case MERGED:
status = MergeResult.MergeStatus.MERGED;
break;
case NOT_SUPPORTED:
status = MergeResult.MergeStatus.NOT_SUPPORTED;
break;
case CHECKOUT_CONFLICT:
status = MergeResult.MergeStatus.CONFLICTING;
break;
default:
throw new IllegalStateException("Unknown merge status " + jGitMergeResult.getMergeStatus());
}
ObjectId[] jGitMergedCommits = jGitMergeResult.getMergedCommits();
List<String> mergedCommits = new ArrayList<>();
if (jGitMergedCommits != null) {
for (ObjectId jGitMergedCommit : jGitMergedCommits) {
mergedCommits.add(jGitMergedCommit.getName());
}
}
List<String> conflicts;
if (org.eclipse.jgit.api.MergeResult.MergeStatus.CHECKOUT_CONFLICT.equals(jGitMergeResult.getMergeStatus())) {
conflicts = jGitMergeResult.getCheckoutConflicts();
} else {
Map<String, int[][]> jGitConflicts = jGitMergeResult.getConflicts();
conflicts = jGitConflicts != null ? new ArrayList<>(jGitConflicts.keySet()) : Collections.emptyList();
}
Map<String, ResolveMerger.MergeFailureReason> jGitFailing = jGitMergeResult.getFailingPaths();
ObjectId newHead = jGitMergeResult.getNewHead();
return newDto(MergeResult.class).withFailed(jGitFailing != null ? new ArrayList<>(jGitFailing.keySet()) : Collections.emptyList())
.withNewHead(newHead != null ? newHead.getName() : null)
.withMergeStatus(status)
.withConflicts(conflicts)
.withMergedCommits(mergedCommits);
}
@Override
public RebaseResponse rebase(String operation, String branch) throws GitException {
RebaseResult result;
RebaseStatus status;
List<String> failed;
List<String> conflicts;
try {
RebaseCommand rebaseCommand = getGit().rebase();
setRebaseOperation(rebaseCommand, operation);
if (branch != null && !branch.isEmpty()) {
rebaseCommand.setUpstream(branch);
}
result = rebaseCommand.call();
} catch (GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
switch (result.getStatus()) {
case ABORTED:
status = RebaseStatus.ABORTED;
break;
case CONFLICTS:
status = RebaseStatus.CONFLICTING;
break;
case UP_TO_DATE:
status = RebaseStatus.ALREADY_UP_TO_DATE;
break;
case FAST_FORWARD:
status = RebaseStatus.FAST_FORWARD;
break;
case NOTHING_TO_COMMIT:
status = RebaseStatus.NOTHING_TO_COMMIT;
break;
case OK:
status = RebaseStatus.OK;
break;
case STOPPED:
status = RebaseStatus.STOPPED;
break;
case UNCOMMITTED_CHANGES:
status = RebaseStatus.UNCOMMITTED_CHANGES;
break;
case EDIT:
status = RebaseStatus.EDITED;
break;
case INTERACTIVE_PREPARED:
status = RebaseStatus.INTERACTIVE_PREPARED;
break;
case STASH_APPLY_CONFLICTS:
status = RebaseStatus.STASH_APPLY_CONFLICTS;
break;
default:
status = RebaseStatus.FAILED;
}
conflicts = result.getConflicts() != null ? result.getConflicts() : Collections.emptyList();
failed = result.getFailingPaths() != null ? new ArrayList<>(result.getFailingPaths().keySet()) : Collections.emptyList();
return newDto(RebaseResponse.class).withStatus(status).withConflicts(conflicts).withFailed(failed);
}
private void setRebaseOperation(RebaseCommand rebaseCommand, String operation) {
RebaseCommand.Operation op = RebaseCommand.Operation.BEGIN;
// If other operation other than 'BEGIN' was specified, set it
if (operation != null) {
switch (operation) {
case REBASE_OPERATION_ABORT:
op = RebaseCommand.Operation.ABORT;
break;
case REBASE_OPERATION_CONTINUE:
op = RebaseCommand.Operation.CONTINUE;
break;
case REBASE_OPERATION_SKIP:
op = RebaseCommand.Operation.SKIP;
break;
default:
op = RebaseCommand.Operation.BEGIN;
break;
}
}
rebaseCommand.setOperation(op);
}
@Override
public void mv(String source, String target) throws GitException {
try {
getGit().add().addFilepattern(target).call();
getGit().rm().addFilepattern(source).call();
} catch (GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public PullResponse pull(PullParams params) throws GitException, UnauthorizedException {
String remoteName = params.getRemote();
String remoteUri;
try {
if (repository.getRepositoryState().equals(RepositoryState.MERGING)) {
throw new GitException(ERROR_PULL_MERGING);
}
String fullBranch = repository.getFullBranch();
if (!fullBranch.startsWith(Constants.R_HEADS)) {
throw new DetachedHeadException(ERROR_PULL_HEAD_DETACHED);
}
String branch = fullBranch.substring(Constants.R_HEADS.length());
StoredConfig config = repository.getConfig();
if (remoteName == null) {
remoteName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
ConfigConstants.CONFIG_KEY_REMOTE);
if (remoteName == null) {
remoteName = Constants.DEFAULT_REMOTE_NAME;
}
}
remoteUri = config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL);
String remoteBranch;
RefSpec fetchRefSpecs = null;
String refSpec = params.getRefSpec();
if (refSpec != null) {
fetchRefSpecs = (refSpec.indexOf(':') < 0) //
? new RefSpec(Constants.R_HEADS + refSpec + ":" + fullBranch) //
: new RefSpec(refSpec);
remoteBranch = fetchRefSpecs.getSource();
} else {
remoteBranch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
ConfigConstants.CONFIG_KEY_MERGE);
}
if (remoteBranch == null) {
remoteBranch = fullBranch;
}
FetchCommand fetchCommand = getGit().fetch();
fetchCommand.setRemote(remoteName);
if (fetchRefSpecs != null) {
fetchCommand.setRefSpecs(fetchRefSpecs);
}
int timeout = params.getTimeout();
if (timeout > 0) {
fetchCommand.setTimeout(timeout);
}
FetchResult fetchResult = (FetchResult)executeRemoteCommand(remoteUri,
fetchCommand,
params.getUsername(),
params.getPassword());
Ref remoteBranchRef = fetchResult.getAdvertisedRef(remoteBranch);
if (remoteBranchRef == null) {
remoteBranchRef = fetchResult.getAdvertisedRef(Constants.R_HEADS + remoteBranch);
}
if (remoteBranchRef == null) {
throw new GitException(format(ERROR_PULL_REF_MISSING, remoteBranch));
}
org.eclipse.jgit.api.MergeResult mergeResult = getGit().merge().include(remoteBranchRef).call();
if (mergeResult.getMergeStatus().equals(org.eclipse.jgit.api.MergeResult.MergeStatus.ALREADY_UP_TO_DATE)) {
return newDto(PullResponse.class).withCommandOutput("Already up-to-date");
}
if (mergeResult.getConflicts() != null) {
StringBuilder message = new StringBuilder(ERROR_PULL_MERGE_CONFLICT_IN_FILES);
message.append(lineSeparator());
Map<String, int[][]> allConflicts = mergeResult.getConflicts();
for (String path : allConflicts.keySet()) {
message.append(path).append(lineSeparator());
}
message.append(ERROR_PULL_AUTO_MERGE_FAILED);
throw new GitException(message.toString());
}
} catch (CheckoutConflictException exception) {
StringBuilder message = new StringBuilder(ERROR_CHECKOUT_CONFLICT);
message.append(lineSeparator());
for (String path : exception.getConflictingPaths()) {
message.append(path).append(lineSeparator());
}
message.append(ERROR_PULL_COMMIT_BEFORE_MERGE);
throw new GitException(message.toString(), exception);
} catch (IOException | GitAPIException exception) {
String errorMessage;
if (exception.getMessage().equals("Invalid remote: " + remoteName)) {
errorMessage = ERROR_NO_REMOTE_REPOSITORY;
} else {
errorMessage = generateExceptionMessage(exception);
}
throw new GitException(errorMessage, exception);
}
return newDto(PullResponse.class).withCommandOutput("Successfully pulled from " + remoteUri);
}
@Override
public PushResponse push(PushParams params) throws GitException, UnauthorizedException {
List<Map<String, String>> updates = new ArrayList<>();
String currentBranch = getCurrentBranch();
String remoteName = params.getRemote();
String remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName,
ConfigConstants.CONFIG_KEY_URL);
PushCommand pushCommand = getGit().push();
if (params.getRemote() != null) {
pushCommand.setRemote(remoteName);
}
List<String> refSpec = params.getRefSpec();
if (!refSpec.isEmpty()) {
pushCommand.setRefSpecs(refSpec.stream()
.map(RefSpec::new)
.collect(Collectors.toList()));
}
pushCommand.setForce(params.isForce());
int timeout = params.getTimeout();
if (timeout > 0) {
pushCommand.setTimeout(timeout);
}
try {
@SuppressWarnings("unchecked")
Iterable<PushResult> pushResults = (Iterable<PushResult>)executeRemoteCommand(remoteUri,
pushCommand,
params.getUsername(),
params.getPassword());
PushResult pushResult = pushResults.iterator().next();
String commandOutput = pushResult.getMessages().isEmpty() ? "Successfully pushed to " + remoteUri : pushResult.getMessages();
Collection<RemoteRefUpdate> refUpdates = pushResult.getRemoteUpdates();
for (RemoteRefUpdate remoteRefUpdate : refUpdates) {
final String remoteRefName = remoteRefUpdate.getRemoteName();
// check status only for branch given in the URL or tags - (handle special "refs/for" case)
String shortenRefFor = remoteRefName.startsWith("refs/for/") ?
remoteRefName.substring("refs/for/".length()) :
remoteRefName;
if (!currentBranch.equals(Repository.shortenRefName(remoteRefName)) && !currentBranch.equals(shortenRefFor)
&& !remoteRefName.startsWith(Constants.R_TAGS)) {
continue;
}
Map<String, String> update = new HashMap<>();
RemoteRefUpdate.Status status = remoteRefUpdate.getStatus();
if (status != RemoteRefUpdate.Status.OK) {
List<String> refSpecs = params.getRefSpec();
if (remoteRefUpdate.getStatus() == RemoteRefUpdate.Status.UP_TO_DATE) {
commandOutput = INFO_PUSH_IGNORED_UP_TO_DATE;
} else {
String remoteBranch = !refSpecs.isEmpty() ? refSpecs.get(0).split(REFSPEC_COLON)[1] : "master";
String errorMessage =
format(ERROR_PUSH_CONFLICTS_PRESENT, currentBranch + BRANCH_REFSPEC_SEPERATOR + remoteBranch, remoteUri);
if (remoteRefUpdate.getMessage() != null) {
errorMessage += "\nError errorMessage: " + remoteRefUpdate.getMessage() + ".";
}
throw new GitException(errorMessage);
}
}
if (status != RemoteRefUpdate.Status.UP_TO_DATE || !remoteRefName.startsWith(Constants.R_TAGS)) {
update.put(KEY_COMMIT_MESSAGE, remoteRefUpdate.getMessage());
update.put(KEY_RESULT, status.name());
TrackingRefUpdate refUpdate = remoteRefUpdate.getTrackingRefUpdate();
if (refUpdate != null) {
update.put(KEY_REMOTENAME, Repository.shortenRefName(refUpdate.getLocalName()));
update.put(KEY_LOCALNAME, Repository.shortenRefName(refUpdate.getRemoteName()));
} else {
update.put(KEY_REMOTENAME, Repository.shortenRefName(remoteRefUpdate.getSrcRef()));
update.put(KEY_LOCALNAME, Repository.shortenRefName(remoteRefUpdate.getRemoteName()));
}
updates.add(update);
}
}
return newDto(PushResponse.class).withCommandOutput(commandOutput).withUpdates(updates);
} catch (GitAPIException exception) {
if ("origin: not found.".equals(exception.getMessage())) {
throw new GitException(ERROR_NO_REMOTE_REPOSITORY, exception);
} else {
String message = generateExceptionMessage(exception);
throw new GitException(message, exception);
}
}
}
@Override
public void remoteAdd(RemoteAddParams params) throws GitException {
String remoteName = params.getName();
if (isNullOrEmpty(remoteName)) {
throw new GitException(ERROR_ADD_REMOTE_NAME_MISSING);
}
StoredConfig config = repository.getConfig();
Set<String> remoteNames = config.getSubsections("remote");
if (remoteNames.contains(remoteName)) {
throw new GitException(format(ERROR_ADD_REMOTE_NAME_ALREADY_EXISTS, remoteName));
}
String url = params.getUrl();
if (isNullOrEmpty(url)) {
throw new GitException(ERROR_ADD_REMOTE_URL_MISSING);
}
RemoteConfig remoteConfig;
try {
remoteConfig = new RemoteConfig(config, remoteName);
} catch (URISyntaxException exception) {
// Not happen since it is newly created remote.
throw new GitException(exception.getMessage(), exception);
}
try {
remoteConfig.addURI(new URIish(url));
} catch (URISyntaxException exception) {
throw new GitException("Remote url " + url + " is invalid. ");
}
List<String> branches = params.getBranches();
if (branches.isEmpty()) {
remoteConfig.addFetchRefSpec(
new RefSpec(Constants.R_HEADS + "*" + ":" + Constants.R_REMOTES + remoteName + "/*").setForceUpdate(true));
} else {
for (String branch : branches) {
remoteConfig.addFetchRefSpec(new RefSpec(Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remoteName + "/" + branch)
.setForceUpdate(true));
}
}
remoteConfig.update(config);
try {
config.save();
} catch (IOException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public void remoteDelete(String name) throws GitException {
StoredConfig config = repository.getConfig();
Set<String> remoteNames = config.getSubsections(ConfigConstants.CONFIG_KEY_REMOTE);
if (!remoteNames.contains(name)) {
throw new GitException("error: Could not remove config section 'remote." + name + "'");
}
config.unsetSection(ConfigConstants.CONFIG_REMOTE_SECTION, name);
Set<String> branches = config.getSubsections(ConfigConstants.CONFIG_BRANCH_SECTION);
for (String branch : branches) {
String r = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
ConfigConstants.CONFIG_KEY_REMOTE);
if (name.equals(r)) {
config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_REMOTE);
config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_MERGE);
List<Branch> remoteBranches = branchList(LIST_REMOTE);
for (Branch remoteBranch : remoteBranches) {
if (remoteBranch.getDisplayName().startsWith(name)) {
branchDelete(remoteBranch.getName(), true);
}
}
}
}
try {
config.save();
} catch (IOException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public List<Remote> remoteList(String remoteName, boolean verbose) throws GitException {
StoredConfig config = repository.getConfig();
Set<String> remoteNames = new HashSet<>(config.getSubsections(ConfigConstants.CONFIG_KEY_REMOTE));
if (remoteName != null && remoteNames.contains(remoteName)) {
remoteNames.clear();
remoteNames.add(remoteName);
}
List<Remote> result = new ArrayList<>(remoteNames.size());
for (String remote : remoteNames) {
try {
List<URIish> uris = new RemoteConfig(config, remote).getURIs();
result.add(newDto(Remote.class).withName(remote).withUrl(uris.isEmpty() ? null : uris.get(0).toString()));
} catch (URISyntaxException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
return result;
}
@Override
public void remoteUpdate(RemoteUpdateParams params) throws GitException {
String remoteName = params.getName();
if (isNullOrEmpty(remoteName)) {
throw new GitException(ERROR_UPDATE_REMOTE_NAME_MISSING);
}
StoredConfig config = repository.getConfig();
Set<String> remoteNames = config.getSubsections(ConfigConstants.CONFIG_KEY_REMOTE);
if (!remoteNames.contains(remoteName)) {
throw new GitException("Remote " + remoteName + " not found. ");
}
RemoteConfig remoteConfig;
try {
remoteConfig = new RemoteConfig(config, remoteName);
} catch (URISyntaxException e) {
throw new GitException(e.getMessage(), e);
}
List<String> branches = params.getBranches();
if (!branches.isEmpty()) {
if (!params.isAddBranches()) {
remoteConfig.setFetchRefSpecs(Collections.emptyList());
remoteConfig.setPushRefSpecs(Collections.emptyList());
} else {
// Replace wildcard refSpec if any.
remoteConfig.removeFetchRefSpec(
new RefSpec(Constants.R_HEADS + "*" + ":" + Constants.R_REMOTES + remoteName + "/*")
.setForceUpdate(true));
remoteConfig.removeFetchRefSpec(
new RefSpec(Constants.R_HEADS + "*" + ":" + Constants.R_REMOTES + remoteName + "/*"));
}
// Add new refSpec.
for (String branch : branches) {
remoteConfig.addFetchRefSpec(
new RefSpec(Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remoteName + "/" + branch)
.setForceUpdate(true));
}
}
// Remove URLs first.
for (String url : params.getRemoveUrl()) {
try {
remoteConfig.removeURI(new URIish(url));
} catch (URISyntaxException e) {
LOG.debug(ERROR_UPDATE_REMOTE_REMOVE_INVALID_URL);
}
}
// Add new URLs.
for (String url : params.getAddUrl()) {
try {
remoteConfig.addURI(new URIish(url));
} catch (URISyntaxException e) {
throw new GitException("Remote url " + url + " is invalid. ");
}
}
// Remove URLs for pushing.
for (String url : params.getRemovePushUrl()) {
try {
remoteConfig.removePushURI(new URIish(url));
} catch (URISyntaxException e) {
LOG.debug(ERROR_UPDATE_REMOTE_REMOVE_INVALID_URL);
}
}
// Add URLs for pushing.
for (String url : params.getAddPushUrl()) {
try {
remoteConfig.addPushURI(new URIish(url));
} catch (URISyntaxException e) {
throw new GitException("Remote push url " + url + " is invalid. ");
}
}
remoteConfig.update(config);
try {
config.save();
} catch (IOException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public void reset(ResetParams params) throws GitException {
try {
ResetCommand resetCommand = getGit().reset();
resetCommand.setRef(params.getCommit());
List<String> patterns = params.getFilePattern();
patterns.forEach(resetCommand::addPath);
if (params.getType() != null && patterns.isEmpty()) {
switch (params.getType()) {
case HARD:
resetCommand.setMode(ResetType.HARD);
break;
case KEEP:
resetCommand.setMode(ResetType.KEEP);
break;
case MERGE:
resetCommand.setMode(ResetType.MERGE);
break;
case MIXED:
resetCommand.setMode(ResetType.MIXED);
break;
case SOFT:
resetCommand.setMode(ResetType.SOFT);
break;
}
}
resetCommand.call();
} catch (GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public void rm(RmParams params) throws GitException {
List<String> files = params.getItems();
RmCommand rmCommand = getGit().rm();
rmCommand.setCached(params.isCached());
if (files != null) {
files.forEach(rmCommand::addFilepattern);
}
try {
rmCommand.call();
} catch (GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public Status status(StatusFormat format) throws GitException {
if (!RepositoryCache.FileKey.isGitRepository(getRepository().getDirectory(), FS.DETECTED)) {
throw new GitException("Not a git repository");
}
String branchName = getCurrentBranch();
return new JGitStatusImpl(branchName, getGit().status(), format);
}
@Override
public Tag tagCreate(TagCreateParams params) throws GitException {
String commit = params.getCommit();
if (commit == null) {
commit = Constants.HEAD;
}
try {
RevWalk revWalk = new RevWalk(repository);
RevObject revObject;
try {
revObject = revWalk.parseAny(repository.resolve(commit));
} finally {
revWalk.close();
}
TagCommand tagCommand = getGit().tag()
.setName(params.getName())
.setObjectId(revObject)
.setMessage(params.getMessage())
.setForceUpdate(params.isForce());
GitUser tagger = getUser();
if (tagger != null) {
tagCommand.setTagger(new PersonIdent(tagger.getName(), tagger.getEmail()));
}
Ref revTagRef = tagCommand.call();
RevTag revTag = revWalk.parseTag(revTagRef.getLeaf().getObjectId());
return newDto(Tag.class).withName(revTag.getTagName());
} catch (IOException | GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public void tagDelete(String name) throws GitException {
try {
Ref tagRef = repository.findRef(name);
if (tagRef == null) {
throw new GitException("Tag " + name + " not found. ");
}
RefUpdate updateRef = repository.updateRef(tagRef.getName());
updateRef.setRefLogMessage("tag deleted", false);
updateRef.setForceUpdate(true);
Result deleteResult = updateRef.delete();
if (deleteResult != Result.FORCED && deleteResult != Result.FAST_FORWARD) {
throw new GitException(format(ERROR_TAG_DELETE, name, deleteResult));
}
} catch (IOException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
@Override
public List<Tag> tagList(String patternStr) throws GitException {
Pattern pattern = null;
if (patternStr != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < patternStr.length(); i++) {
char c = patternStr.charAt(i);
if (c == '*' || c == '?') {
sb.append('.');
} else if (c == '.' || c == '(' || c == ')' || c == '[' || c == ']' || c == '^' || c == '$'
|| c == '|') {
sb.append('\\');
}
sb.append(c);
}
pattern = Pattern.compile(sb.toString());
}
Set<String> tagNames = repository.getTags().keySet();
List<Tag> tags = new ArrayList<>(tagNames.size());
for (String tagName : tagNames) {
if (pattern == null || pattern.matcher(tagName).matches()) {
tags.add(newDto(Tag.class).withName(tagName));
}
}
return tags;
}
@Override
public void close() {
repository.close();
}
@Override
public File getWorkingDir() {
return repository.getWorkTree();
}
@Override
public List<RemoteReference> lsRemote(String remoteUrl) throws UnauthorizedException, GitException {
LsRemoteCommand lsRemoteCommand = getGit().lsRemote().setRemote(remoteUrl);
Collection<Ref> refs;
try {
refs = lsRemoteCommand.call();
} catch (GitAPIException exception) {
if (exception.getMessage().contains(ERROR_AUTHENTICATION_REQUIRED)) {
throw new UnauthorizedException(format(ERROR_AUTHENTICATION_FAILED, remoteUrl));
} else {
throw new GitException(exception.getMessage(), exception);
}
}
return refs.stream()
.map(ref -> newDto(RemoteReference.class).withCommitId(ref.getObjectId().name()).withReferenceName(ref.getName()))
.collect(Collectors.toList());
}
@Override
public Config getConfig() throws GitException {
if (config != null) {
return config;
}
return config = new JGitConfigImpl(repository);
}
@Override
public void setOutputLineConsumerFactory(LineConsumerFactory lineConsumerFactory) {
this.lineConsumerFactory = lineConsumerFactory;
}
private Git getGit() {
if (git != null) {
return git;
}
return git = new Git(repository);
}
@Override
public List<String> listFiles(LsFilesParams params) throws GitException {
return Arrays.asList(getWorkingDir().list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
}));
}
@Override
public void cloneWithSparseCheckout(String directory, String remoteUrl) throws GitException, UnauthorizedException {
//TODO rework this code when jgit will support sparse-checkout. Tracked issue: https://bugs.eclipse.org/bugs/show_bug.cgi?id=383772
if (directory == null) {
throw new GitException("Subdirectory for sparse-checkout is not specified");
}
clone(CloneParams.create(remoteUrl));
final String sourcePath = getWorkingDir().getPath();
final String keepDirectoryPath = sourcePath + "/" + directory;
IOFileFilter folderFilter = new DirectoryFileFilter() {
public boolean accept(File dir) {
String directoryPath = dir.getPath();
return !(directoryPath.startsWith(keepDirectoryPath) || directoryPath.startsWith(sourcePath + "/.git"));
}
};
Collection<File> files = org.apache.commons.io.FileUtils.listFilesAndDirs(getWorkingDir(), TrueFileFilter.INSTANCE, folderFilter);
try {
DirCache index = getRepository().lockDirCache();
int sourcePathLength = sourcePath.length() + 1;
files.stream()
.filter(File::isFile)
.forEach(file -> index.getEntry(file.getPath().substring(sourcePathLength)).setAssumeValid(true));
index.write();
index.commit();
for (File file : files) {
if (keepDirectoryPath.startsWith(file.getPath())) {
continue;
}
if (file.exists()) {
FileUtils.delete(file, FileUtils.RECURSIVE);
}
}
} catch (IOException exception) {
String message = generateExceptionMessage(exception);
throw new GitException(message, exception);
}
}
/**
* Execute remote jgit command.
*
* @param remoteUrl
* remote url
* @param command
* command to execute
* @return executed command
* @throws GitException
* @throws GitAPIException
* @throws UnauthorizedException
*/
@VisibleForTesting
Object executeRemoteCommand(String remoteUrl, TransportCommand command, @Nullable String username, @Nullable String password)
throws GitException, GitAPIException, UnauthorizedException {
File keyDirectory = null;
UserCredential credentials = null;
try {
if (GitUrlUtils.isSSH(remoteUrl)) {
keyDirectory = Files.createTempDir();
final File sshKey = writePrivateKeyFile(remoteUrl, keyDirectory);
SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
session.setConfig("StrictHostKeyChecking", "no");
}
@Override
protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
JSch jsch = super.getJSch(hc, fs);
jsch.removeAllIdentity();
jsch.addIdentity(sshKey.getAbsolutePath());
return jsch;
}
};
command.setTransportConfigCallback(transport -> {
// If recursive clone is performed and git-module added by http(s) url is present in the cloned project,
// transport will be instance of TransportHttp in the step of cloning this module
if (transport instanceof SshTransport) {
((SshTransport)transport).setSshSessionFactory(sshSessionFactory);
}
});
} else {
if (remoteUrl != null && GIT_URL_WITH_CREDENTIALS_PATTERN.matcher(remoteUrl).matches()) {
username = remoteUrl.substring(remoteUrl.indexOf("://") + 3, remoteUrl.lastIndexOf(":"));
password = remoteUrl.substring(remoteUrl.lastIndexOf(":") + 1, remoteUrl.indexOf("@"));
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
} else {
if (username != null && password != null) {
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
} else {
credentials = credentialsLoader.getUserCredential(remoteUrl);
if (credentials != null) {
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(credentials.getUserName(),
credentials.getPassword()));
}
}
}
}
ProxyAuthenticator.initAuthenticator(remoteUrl);
return command.call();
} catch (GitException | TransportException exception) {
if ("Unable get private ssh key".equals(exception.getMessage())) {
throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY);
} else if (exception.getMessage().contains(ERROR_AUTHENTICATION_REQUIRED)) {
final ProviderInfo info = credentialsLoader.getProviderInfo(remoteUrl);
if (info != null) {
throw new UnauthorizedException(exception.getMessage(),
ErrorCodes.UNAUTHORIZED_GIT_OPERATION,
ImmutableMap.of(PROVIDER_NAME, info.getProviderName(),
AUTHENTICATE_URL, info.getAuthenticateUrl(),
"authenticated", Boolean.toString(credentials != null)));
}
throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION);
} else {
throw exception;
}
} finally {
if (keyDirectory != null && keyDirectory.exists()) {
try {
FileUtils.delete(keyDirectory, FileUtils.RECURSIVE);
} catch (IOException exception) {
throw new GitException("Can't remove SSH key directory", exception);
}
}
ProxyAuthenticator.resetAuthenticator();
}
}
/**
* Writes private SSH key into file.
*
* @return file that contains SSH key
* @throws GitException
* if other error occurs
*/
private File writePrivateKeyFile(String url, File keyDirectory) throws GitException {
final File keyFile = new File(keyDirectory, "identity");
try (FileOutputStream fos = new FileOutputStream(keyFile)) {
byte[] sshKey = sshKeyProvider.getPrivateKey(url);
fos.write(sshKey);
} catch (IOException | ServerException exception) {
String errorMessage = "Can't store ssh key. ".concat(exception.getMessage());
LOG.error(errorMessage, exception);
throw new GitException(errorMessage, ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY);
}
Set<PosixFilePermission> permissions = EnumSet.of(OWNER_READ, OWNER_WRITE);
try {
java.nio.file.Files.setPosixFilePermissions(keyFile.toPath(), permissions);
} catch (IOException exception) {
throw new GitException(exception.getMessage(), exception);
}
return keyFile;
}
private GitUser getUser() throws GitException {
return userResolver.getUser();
}
private void deleteRepositoryFolder() {
try {
if (repository.getDirectory().exists()) {
FileUtils.delete(repository.getDirectory(), FileUtils.RECURSIVE | FileUtils.IGNORE_ERRORS);
}
} catch (Exception exception) {
// Ignore the error since we want to throw the original error
LOG.error("Could not remove .git folder in path " + repository.getDirectory().getPath(), exception);
}
}
private Repository getRepository() {
return repository;
}
/**
* Get the current branch on the current directory
*
* @return the name of the branch
* @throws GitException
* if any exception occurs
*/
public String getCurrentBranch() throws GitException {
try {
return Repository.shortenRefName(repository.exactRef(Constants.HEAD).getLeaf().getName());
} catch (IOException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
/**
* Method for cleaning name of remote branch to be checked out. I.e. it
* takes something like "origin/testBranch" and returns "testBranch". This
* is needed for view-compatibility with console Git client.
*
* @param branchName
* is a name of branch to be cleaned
* @return branchName without remote repository name
* @throws GitException
*/
private String cleanRemoteName(String branchName) throws GitException {
String returnName = branchName;
List<Remote> remotes = this.remoteList(null, false);
for (Remote remote : remotes) {
if (branchName.startsWith(remote.getName())) {
returnName = branchName.replaceFirst(remote.getName() + "/", "");
}
}
return returnName;
}
/**
* Method for generate exception message. The default logic return message from the error.
* It also check if the type of the message is for SSL or in case that the error
* start with "file name to long" then it raise the relevant message
*
* @param error
* throwable error
* @return exception message
*/
private String generateExceptionMessage(Throwable error) {
String message = error.getMessage();
while (error.getCause() != null) {
//if e caused by an SSLHandshakeException - replace thrown message with a hardcoded message
if (error.getCause() instanceof SSLHandshakeException) {
message = "The system is not configured to trust the security certificate provided by the Git server";
break;
} else if (error.getCause() instanceof IOException) {
// Security fix - error message should not include complete local file path on the target system
// Error message for example - File name too long (path /xx/xx/xx/xx/xx/xx/xx/xx /, working dir /xx/xx/xx)
if (message != null && message.startsWith(FILE_NAME_TOO_LONG_ERROR_PREFIX)) {
try {
String repoPath = repository.getWorkTree().getCanonicalPath();
int startIndex = message.indexOf(repoPath);
int endIndex = message.indexOf(",");
if (startIndex > -1 && endIndex > -1) {
message = FILE_NAME_TOO_LONG_ERROR_PREFIX + " " + message.substring(startIndex + repoPath.length(), endIndex);
}
break;
} catch (IOException e) {
//Hide exception as it is only needed for this message generation
}
}
}
error = error.getCause();
}
return message;
}
}
| epl-1.0 |
lbchen/ODL | opendaylight/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICoordinatorChangeAware.java | 849 |
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
/**
* @file ICoordinatorChangeAware.java
*
*
* @brief Interface that needs to be implemented by who wants to be
* notified of coordinator role change
*
*/
package org.opendaylight.controller.clustering.services;
/**
* Interface that needs to be implemented by who wants to be
* notified of coordinator role change
*
*/
public interface ICoordinatorChangeAware {
/**
* Function that will be called when there is the event of
* coordinator change in the cluster.
*/
public void coordinatorChanged();
}
| epl-1.0 |
rex-xxx/mt6572_x201 | external/jmonkeyengine/engine/src/tools/jme3tools/converters/model/strip/VertexCache.java | 2974 | /*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package jme3tools.converters.model.strip;
import java.util.Arrays;
class VertexCache {
int[] entries;
int numEntries;
public VertexCache() {
this(16);
}
public VertexCache(int size) {
numEntries = size;
entries = new int[numEntries];
clear();
}
public boolean inCache(int entry) {
for(int i = 0; i < numEntries; i++)
{
if(entries[i] == entry)
{
return true;
}
}
return false;
}
public int addEntry(int entry) {
int removed;
removed = entries[numEntries - 1];
//push everything right one
for(int i = numEntries - 2; i >= 0; i--)
{
entries[i + 1] = entries[i];
}
entries[0] = entry;
return removed;
}
public void clear() {
Arrays.fill(entries,-1);
}
public int at(int index) {
return entries[index];
}
public void set(int index, int value) {
entries[index] = value;
}
public void copy(VertexCache inVcache)
{
for(int i = 0; i < numEntries; i++)
{
inVcache.set(i, entries[i]);
}
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | external/jsilver/src/com/google/clearsilver/jsilver/compiler/VariableTranslator.java | 5492 | /*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.clearsilver.jsilver.compiler;
import static com.google.clearsilver.jsilver.compiler.JavaExpression.StringExpression;
import static com.google.clearsilver.jsilver.compiler.JavaExpression.Type;
import static com.google.clearsilver.jsilver.compiler.JavaExpression.literal;
import com.google.clearsilver.jsilver.syntax.analysis.DepthFirstAdapter;
import com.google.clearsilver.jsilver.syntax.node.ADecNumberVariable;
import com.google.clearsilver.jsilver.syntax.node.ADescendVariable;
import com.google.clearsilver.jsilver.syntax.node.AExpandVariable;
import com.google.clearsilver.jsilver.syntax.node.AHexNumberVariable;
import com.google.clearsilver.jsilver.syntax.node.ANameVariable;
import com.google.clearsilver.jsilver.syntax.node.PVariable;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
/**
* Translates a variable name (e.g. search.results.3.title) into the Java code for use as a key in
* looking up a variable (e.g. "search.results.3.title").
*
* While it is possible to reuse an instance of this class repeatedly, it is not thread safe or
* reentrant. Evaluating an expression such as: <code>a.b[c.d]</code> would require two instances.
*/
public class VariableTranslator extends DepthFirstAdapter {
private List<JavaExpression> components;
private final ExpressionTranslator expressionTranslator;
public VariableTranslator(ExpressionTranslator expressionTranslator) {
this.expressionTranslator = expressionTranslator;
}
/**
* See class description.
*
* @param csVariable Variable node in template's AST.
* @return Appropriate code (as JavaExpression).
*/
public JavaExpression translate(PVariable csVariable) {
try {
assert components == null;
components = new ArrayList<JavaExpression>();
csVariable.apply(this);
components = joinComponentsWithDots(components);
components = combineAdjacentStrings(components);
return concatenate(components);
} finally {
components = null;
}
}
@Override
public void caseANameVariable(ANameVariable node) {
components.add(new StringExpression(node.getWord().getText()));
}
@Override
public void caseADecNumberVariable(ADecNumberVariable node) {
components.add(new StringExpression(node.getDecNumber().getText()));
}
@Override
public void caseAHexNumberVariable(AHexNumberVariable node) {
components.add(new StringExpression(node.getHexNumber().getText()));
}
@Override
public void caseADescendVariable(ADescendVariable node) {
node.getParent().apply(this);
node.getChild().apply(this);
}
@Override
public void caseAExpandVariable(AExpandVariable node) {
node.getParent().apply(this);
components.add(expressionTranslator.translateToString(node.getChild()));
}
/**
* Inserts dots between each component in the path.
*
* e.g. from: "a", "b", something, "c" to: "a", ".", "b", ".", something, ".", "c"
*/
private List<JavaExpression> joinComponentsWithDots(List<JavaExpression> in) {
List<JavaExpression> out = new ArrayList<JavaExpression>(in.size() * 2);
for (JavaExpression component : in) {
if (!out.isEmpty()) {
out.add(DOT);
}
out.add(component);
}
return out;
}
private static final JavaExpression DOT = new StringExpression(".");
/**
* Combines adjacent strings.
*
* e.g. from: "a", ".", "b", ".", something, ".", "c" to : "a.b.", something, ".c"
*/
private List<JavaExpression> combineAdjacentStrings(List<JavaExpression> in) {
assert !in.isEmpty();
List<JavaExpression> out = new ArrayList<JavaExpression>(in.size());
JavaExpression last = null;
for (JavaExpression current : in) {
if (last == null) {
last = current;
continue;
}
if (current instanceof StringExpression && last instanceof StringExpression) {
// Last and current are both strings - combine them.
StringExpression currentString = (StringExpression) current;
StringExpression lastString = (StringExpression) last;
last = new StringExpression(lastString.getValue() + currentString.getValue());
} else {
out.add(last);
last = current;
}
}
out.add(last);
return out;
}
/**
* Concatenate a list of JavaExpressions into a single string.
*
* e.g. from: "a", "b", stuff to : "a" + "b" + stuff
*/
private JavaExpression concatenate(List<JavaExpression> expressions) {
StringWriter buffer = new StringWriter();
PrintWriter out = new PrintWriter(buffer);
boolean seenFirst = false;
for (JavaExpression expression : expressions) {
if (seenFirst) {
out.print(" + ");
}
seenFirst = true;
expression.write(out);
}
return literal(Type.VAR_NAME, buffer.toString());
}
}
| gpl-2.0 |
filipefilardi/Telegram | TMessagesProj/src/main/java/org/telegram/ui/Adapters/MentionsAdapter.java | 52244 | /*
* This is the source code of Telegram for Android v. 3.x.x
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2017.
*/
package org.telegram.ui.Adapters;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.EmojiSuggestion;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.R;
import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.query.SearchQuery;
import org.telegram.messenger.support.widget.RecyclerView;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.BotSwitchCell;
import org.telegram.ui.Cells.ContextLinkCell;
import org.telegram.ui.Cells.MentionCell;
import org.telegram.ui.ChatActivity;
import org.telegram.ui.Components.RecyclerListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
public class MentionsAdapter extends RecyclerListView.SelectionAdapter {
public interface MentionsAdapterDelegate {
void needChangePanelVisibility(boolean show);
void onContextSearch(boolean searching);
void onContextClick(TLRPC.BotInlineResult result);
}
private Context mContext;
private long dialog_id;
private TLRPC.ChatFull info;
private SearchAdapterHelper searchAdapterHelper;
private ArrayList<TLRPC.User> searchResultUsernames;
private HashMap<Integer, TLRPC.User> searchResultUsernamesMap;
private Runnable searchGlobalRunnable;
private ArrayList<String> searchResultHashtags;
private ArrayList<String> searchResultCommands;
private ArrayList<String> searchResultCommandsHelp;
private ArrayList<EmojiSuggestion> searchResultSuggestions;
private ArrayList<TLRPC.User> searchResultCommandsUsers;
private ArrayList<TLRPC.BotInlineResult> searchResultBotContext;
private TLRPC.TL_inlineBotSwitchPM searchResultBotContextSwitch;
private HashMap<String, TLRPC.BotInlineResult> searchResultBotContextById;
private MentionsAdapterDelegate delegate;
private HashMap<Integer, TLRPC.BotInfo> botInfo;
private int resultStartPosition;
private boolean allowNewMentions = true;
private int resultLength;
private String lastText;
private boolean lastUsernameOnly;
private int lastPosition;
private ArrayList<MessageObject> messages;
private boolean needUsernames = true;
private boolean needBotContext = true;
private boolean isDarkTheme;
private int botsCount;
private boolean inlineMediaEnabled = true;
private int channelLastReqId;
private int channelReqId;
private boolean isSearchingMentions;
private String searchingContextUsername;
private String searchingContextQuery;
private String nextQueryOffset;
private int contextUsernameReqid;
private int contextQueryReqid;
private boolean noUserName;
private TLRPC.User foundContextBot;
private boolean contextMedia;
private Runnable contextQueryRunnable;
private Location lastKnownLocation;
private ChatActivity parentFragment;
private SendMessagesHelper.LocationProvider locationProvider = new SendMessagesHelper.LocationProvider(new SendMessagesHelper.LocationProvider.LocationProviderDelegate() {
@Override
public void onLocationAcquired(Location location) {
if (foundContextBot != null && foundContextBot.bot_inline_geo) {
lastKnownLocation = location;
searchForContextBotResults(true, foundContextBot, searchingContextQuery, "");
}
}
@Override
public void onUnableLocationAcquire() {
onLocationUnavailable();
}
}) {
@Override
public void stop() {
super.stop();
lastKnownLocation = null;
}
};
public MentionsAdapter(Context context, boolean darkTheme, long did, MentionsAdapterDelegate mentionsAdapterDelegate) {
mContext = context;
delegate = mentionsAdapterDelegate;
isDarkTheme = darkTheme;
dialog_id = did;
searchAdapterHelper = new SearchAdapterHelper();
searchAdapterHelper.setDelegate(new SearchAdapterHelper.SearchAdapterHelperDelegate() {
@Override
public void onDataSetChanged() {
notifyDataSetChanged();
}
@Override
public void onSetHashtags(ArrayList<SearchAdapterHelper.HashtagObject> arrayList, HashMap<String, SearchAdapterHelper.HashtagObject> hashMap) {
if (lastText != null) {
searchUsernameOrHashtag(lastText, lastPosition, messages, lastUsernameOnly);
}
}
});
}
public void onDestroy() {
if (locationProvider != null) {
locationProvider.stop();
}
if (contextQueryRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(contextQueryRunnable);
contextQueryRunnable = null;
}
if (contextUsernameReqid != 0) {
ConnectionsManager.getInstance().cancelRequest(contextUsernameReqid, true);
contextUsernameReqid = 0;
}
if (contextQueryReqid != 0) {
ConnectionsManager.getInstance().cancelRequest(contextQueryReqid, true);
contextQueryReqid = 0;
}
foundContextBot = null;
inlineMediaEnabled = true;
searchingContextUsername = null;
searchingContextQuery = null;
noUserName = false;
}
public void setAllowNewMentions(boolean value) {
allowNewMentions = value;
}
public void setParentFragment(ChatActivity fragment) {
parentFragment = fragment;
}
public void setChatInfo(TLRPC.ChatFull chatInfo) {
info = chatInfo;
if (!inlineMediaEnabled && foundContextBot != null && parentFragment != null) {
TLRPC.Chat chat = parentFragment.getCurrentChat();
if (chat != null) {
inlineMediaEnabled = ChatObject.canSendStickers(chat);
if (inlineMediaEnabled) {
searchResultUsernames = null;
notifyDataSetChanged();
delegate.needChangePanelVisibility(false);
processFoundUser(foundContextBot);
}
}
}
if (lastText != null) {
searchUsernameOrHashtag(lastText, lastPosition, messages, lastUsernameOnly);
}
}
public void setNeedUsernames(boolean value) {
needUsernames = value;
}
public void setNeedBotContext(boolean value) {
needBotContext = value;
}
public void setBotInfo(HashMap<Integer, TLRPC.BotInfo> info) {
botInfo = info;
}
public void setBotsCount(int count) {
botsCount = count;
}
public void clearRecentHashtags() {
searchAdapterHelper.clearRecentHashtags();
searchResultHashtags.clear();
notifyDataSetChanged();
if (delegate != null) {
delegate.needChangePanelVisibility(false);
}
}
public TLRPC.TL_inlineBotSwitchPM getBotContextSwitch() {
return searchResultBotContextSwitch;
}
public int getContextBotId() {
return foundContextBot != null ? foundContextBot.id : 0;
}
public TLRPC.User getContextBotUser() {
return foundContextBot != null ? foundContextBot : null;
}
public String getContextBotName() {
return foundContextBot != null ? foundContextBot.username : "";
}
private void processFoundUser(TLRPC.User user) {
contextUsernameReqid = 0;
locationProvider.stop();
if (user != null && user.bot && user.bot_inline_placeholder != null) {
foundContextBot = user;
if (parentFragment != null) {
TLRPC.Chat chat = parentFragment.getCurrentChat();
if (chat != null) {
inlineMediaEnabled = ChatObject.canSendStickers(chat);
if (!inlineMediaEnabled) {
notifyDataSetChanged();
delegate.needChangePanelVisibility(true);
return;
}
}
}
if (foundContextBot.bot_inline_geo) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
boolean allowGeo = preferences.getBoolean("inlinegeo_" + foundContextBot.id, false);
if (!allowGeo && parentFragment != null && parentFragment.getParentActivity() != null) {
final TLRPC.User foundContextBotFinal = foundContextBot;
AlertDialog.Builder builder = new AlertDialog.Builder(parentFragment.getParentActivity());
builder.setTitle(LocaleController.getString("ShareYouLocationTitle", R.string.ShareYouLocationTitle));
builder.setMessage(LocaleController.getString("ShareYouLocationInline", R.string.ShareYouLocationInline));
final boolean buttonClicked[] = new boolean[1];
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
buttonClicked[0] = true;
if (foundContextBotFinal != null) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
preferences.edit().putBoolean("inlinegeo_" + foundContextBotFinal.id, true).commit();
checkLocationPermissionsOrStart();
}
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
buttonClicked[0] = true;
onLocationUnavailable();
}
});
parentFragment.showDialog(builder.create(), new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (!buttonClicked[0]) {
onLocationUnavailable();
}
}
});
} else {
checkLocationPermissionsOrStart();
}
}
} else {
foundContextBot = null;
inlineMediaEnabled = true;
}
if (foundContextBot == null) {
noUserName = true;
} else {
if (delegate != null) {
delegate.onContextSearch(true);
}
searchForContextBotResults(true, foundContextBot, searchingContextQuery, "");
}
}
private void searchForContextBot(final String username, final String query) {
if (foundContextBot != null && foundContextBot.username != null && foundContextBot.username.equals(username) && searchingContextQuery != null && searchingContextQuery.equals(query)) {
return;
}
searchResultBotContext = null;
searchResultBotContextById = null;
searchResultBotContextSwitch = null;
notifyDataSetChanged();
if (foundContextBot != null) {
if (!inlineMediaEnabled && username != null && query != null) {
return;
}
delegate.needChangePanelVisibility(false);
}
if (contextQueryRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(contextQueryRunnable);
contextQueryRunnable = null;
}
if (TextUtils.isEmpty(username) || searchingContextUsername != null && !searchingContextUsername.equals(username)) {
if (contextUsernameReqid != 0) {
ConnectionsManager.getInstance().cancelRequest(contextUsernameReqid, true);
contextUsernameReqid = 0;
}
if (contextQueryReqid != 0) {
ConnectionsManager.getInstance().cancelRequest(contextQueryReqid, true);
contextQueryReqid = 0;
}
foundContextBot = null;
inlineMediaEnabled = true;
searchingContextUsername = null;
searchingContextQuery = null;
locationProvider.stop();
noUserName = false;
if (delegate != null) {
delegate.onContextSearch(false);
}
if (username == null || username.length() == 0) {
return;
}
}
if (query == null) {
if (contextQueryReqid != 0) {
ConnectionsManager.getInstance().cancelRequest(contextQueryReqid, true);
contextQueryReqid = 0;
}
searchingContextQuery = null;
if (delegate != null) {
delegate.onContextSearch(false);
}
return;
}
if (delegate != null) {
if (foundContextBot != null) {
delegate.onContextSearch(true);
} else if (username.equals("gif")) {
searchingContextUsername = "gif";
delegate.onContextSearch(false);
}
}
searchingContextQuery = query;
contextQueryRunnable = new Runnable() {
@Override
public void run() {
if (contextQueryRunnable != this) {
return;
}
contextQueryRunnable = null;
if (foundContextBot != null || noUserName) {
if (noUserName) {
return;
}
searchForContextBotResults(true, foundContextBot, query, "");
} else {
searchingContextUsername = username;
TLObject object = MessagesController.getInstance().getUserOrChat(searchingContextUsername);
if (object instanceof TLRPC.User) {
processFoundUser((TLRPC.User) object);
} else {
TLRPC.TL_contacts_resolveUsername req = new TLRPC.TL_contacts_resolveUsername();
req.username = searchingContextUsername;
contextUsernameReqid = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (searchingContextUsername == null || !searchingContextUsername.equals(username)) {
return;
}
TLRPC.User user = null;
if (error == null) {
TLRPC.TL_contacts_resolvedPeer res = (TLRPC.TL_contacts_resolvedPeer) response;
if (!res.users.isEmpty()) {
user = res.users.get(0);
MessagesController.getInstance().putUser(user, false);
MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true);
}
}
processFoundUser(user);
}
});
}
});
}
}
}
};
AndroidUtilities.runOnUIThread(contextQueryRunnable, 400);
}
private void onLocationUnavailable() {
if (foundContextBot != null && foundContextBot.bot_inline_geo) {
lastKnownLocation = new Location("network");
lastKnownLocation.setLatitude(-1000);
lastKnownLocation.setLongitude(-1000);
searchForContextBotResults(true, foundContextBot, searchingContextQuery, "");
}
}
private void checkLocationPermissionsOrStart() {
if (parentFragment == null || parentFragment.getParentActivity() == null) {
return;
}
if (Build.VERSION.SDK_INT >= 23 && parentFragment.getParentActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
parentFragment.getParentActivity().requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 2);
return;
}
if (foundContextBot != null && foundContextBot.bot_inline_geo) {
locationProvider.start();
}
}
public void setSearchingMentions(boolean value) {
isSearchingMentions = value;
}
public String getBotCaption() {
if (foundContextBot != null) {
return foundContextBot.bot_inline_placeholder;
} else if (searchingContextUsername != null && searchingContextUsername.equals("gif")) {
return "Search GIFs";
}
return null;
}
public void searchForContextBotForNextOffset() {
if (contextQueryReqid != 0 || nextQueryOffset == null || nextQueryOffset.length() == 0 || foundContextBot == null || searchingContextQuery == null) {
return;
}
searchForContextBotResults(true, foundContextBot, searchingContextQuery, nextQueryOffset);
}
private void searchForContextBotResults(final boolean cache, final TLRPC.User user, final String query, final String offset) {
if (contextQueryReqid != 0) {
ConnectionsManager.getInstance().cancelRequest(contextQueryReqid, true);
contextQueryReqid = 0;
}
if (!inlineMediaEnabled) {
if (delegate != null) {
delegate.onContextSearch(false);
}
return;
}
if (query == null || user == null) {
searchingContextQuery = null;
return;
}
if (user.bot_inline_geo && lastKnownLocation == null) {
return;
}
final String key = dialog_id + "_" + query + "_" + offset + "_" + dialog_id + "_" + user.id + "_" + (user.bot_inline_geo && lastKnownLocation != null && lastKnownLocation.getLatitude() != -1000 ? lastKnownLocation.getLatitude() + lastKnownLocation.getLongitude() : "");
RequestDelegate requestDelegate = new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (searchingContextQuery == null || !query.equals(searchingContextQuery)) {
return;
}
contextQueryReqid = 0;
if (cache && response == null) {
searchForContextBotResults(false, user, query, offset);
} else if (delegate != null) {
delegate.onContextSearch(false);
}
if (response != null) {
TLRPC.TL_messages_botResults res = (TLRPC.TL_messages_botResults) response;
if (!cache && res.cache_time != 0) {
MessagesStorage.getInstance().saveBotCache(key, res);
}
nextQueryOffset = res.next_offset;
if (searchResultBotContextById == null) {
searchResultBotContextById = new HashMap<>();
searchResultBotContextSwitch = res.switch_pm;
}
for (int a = 0; a < res.results.size(); a++) {
TLRPC.BotInlineResult result = res.results.get(a);
if (searchResultBotContextById.containsKey(result.id) || !(result.document instanceof TLRPC.TL_document) && !(result.photo instanceof TLRPC.TL_photo) && result.content_url == null && result.send_message instanceof TLRPC.TL_botInlineMessageMediaAuto) {
res.results.remove(a);
a--;
}
result.query_id = res.query_id;
searchResultBotContextById.put(result.id, result);
}
boolean added = false;
if (searchResultBotContext == null || offset.length() == 0) {
searchResultBotContext = res.results;
contextMedia = res.gallery;
} else {
added = true;
searchResultBotContext.addAll(res.results);
if (res.results.isEmpty()) {
nextQueryOffset = "";
}
}
searchResultHashtags = null;
searchResultUsernames = null;
searchResultUsernamesMap = null;
searchResultCommands = null;
searchResultSuggestions = null;
searchResultCommandsHelp = null;
searchResultCommandsUsers = null;
if (added) {
boolean hasTop = searchResultBotContextSwitch != null;
notifyItemChanged(searchResultBotContext.size() - res.results.size() + (hasTop ? 1 : 0) - 1);
notifyItemRangeInserted(searchResultBotContext.size() - res.results.size() + (hasTop ? 1 : 0), res.results.size());
} else {
notifyDataSetChanged();
}
delegate.needChangePanelVisibility(!searchResultBotContext.isEmpty() || searchResultBotContextSwitch != null);
}
}
});
}
};
if (cache) {
MessagesStorage.getInstance().getBotCache(key, requestDelegate);
} else {
TLRPC.TL_messages_getInlineBotResults req = new TLRPC.TL_messages_getInlineBotResults();
req.bot = MessagesController.getInputUser(user);
req.query = query;
req.offset = offset;
if (user.bot_inline_geo && lastKnownLocation != null && lastKnownLocation.getLatitude() != -1000) {
req.flags |= 1;
req.geo_point = new TLRPC.TL_inputGeoPoint();
req.geo_point.lat = lastKnownLocation.getLatitude();
req.geo_point._long = lastKnownLocation.getLongitude();
}
int lower_id = (int) dialog_id;
int high_id = (int) (dialog_id >> 32);
if (lower_id != 0) {
req.peer = MessagesController.getInputPeer(lower_id);
} else {
req.peer = new TLRPC.TL_inputPeerEmpty();
}
contextQueryReqid = ConnectionsManager.getInstance().sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors);
}
}
public void searchUsernameOrHashtag(String text, int position, ArrayList<MessageObject> messageObjects, boolean usernameOnly) {
if (channelReqId != 0) {
ConnectionsManager.getInstance().cancelRequest(channelReqId, true);
channelReqId = 0;
}
if (searchGlobalRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(searchGlobalRunnable);
searchGlobalRunnable = null;
}
if (TextUtils.isEmpty(text)) {
searchForContextBot(null, null);
delegate.needChangePanelVisibility(false);
lastText = null;
return;
}
int searchPostion = position;
if (text.length() > 0) {
searchPostion--;
}
lastText = null;
lastUsernameOnly = usernameOnly;
StringBuilder result = new StringBuilder();
int foundType = -1;
boolean hasIllegalUsernameCharacters = false;
if (!usernameOnly && needBotContext && text.charAt(0) == '@') {
int index = text.indexOf(' ');
int len = text.length();
String username = null;
String query = null;
if (index > 0) {
username = text.substring(1, index);
query = text.substring(index + 1);
} else if (text.charAt(len - 1) == 't' && text.charAt(len - 2) == 'o' && text.charAt(len - 3) == 'b') {
username = text.substring(1);
query = "";
} else {
searchForContextBot(null, null);
}
if (username != null && username.length() >= 1) {
for (int a = 1; a < username.length(); a++) {
char ch = username.charAt(a);
if (!(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_')) {
username = "";
break;
}
}
} else {
username = "";
}
searchForContextBot(username, query);
} else {
searchForContextBot(null, null);
}
if (foundContextBot != null) {
return;
}
int dogPostion = -1;
if (usernameOnly) {
result.append(text.substring(1));
resultStartPosition = 0;
resultLength = result.length();
foundType = 0;
} else {
for (int a = searchPostion; a >= 0; a--) {
if (a >= text.length()) {
continue;
}
char ch = text.charAt(a);
if (a == 0 || text.charAt(a - 1) == ' ' || text.charAt(a - 1) == '\n') {
if (ch == '@') {
if (needUsernames || needBotContext && a == 0) {
if (info == null && a != 0) {
lastText = text;
lastPosition = position;
messages = messageObjects;
delegate.needChangePanelVisibility(false);
return;
}
dogPostion = a;
foundType = 0;
resultStartPosition = a;
resultLength = result.length() + 1;
break;
}
} else if (ch == '#') {
if (searchAdapterHelper.loadRecentHashtags()) {
foundType = 1;
resultStartPosition = a;
resultLength = result.length() + 1;
result.insert(0, ch);
break;
} else {
lastText = text;
lastPosition = position;
messages = messageObjects;
delegate.needChangePanelVisibility(false);
return;
}
} else if (a == 0 && botInfo != null && ch == '/') {
foundType = 2;
resultStartPosition = a;
resultLength = result.length() + 1;
break;
} else if (ch == ':' && result.length() > 0) {
foundType = 3;
resultStartPosition = a;
resultLength = result.length() + 1;
break;
}
}
if (!(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_')) {
hasIllegalUsernameCharacters = true;
}
result.insert(0, ch);
}
}
if (foundType == -1) {
delegate.needChangePanelVisibility(false);
return;
}
if (foundType == 0) {
final ArrayList<Integer> users = new ArrayList<>();
for (int a = 0; a < Math.min(100, messageObjects.size()); a++) {
int from_id = messageObjects.get(a).messageOwner.from_id;
if (!users.contains(from_id)) {
users.add(from_id);
}
}
final String usernameString = result.toString().toLowerCase();
boolean hasSpace = usernameString.indexOf(' ') >= 0;
ArrayList<TLRPC.User> newResult = new ArrayList<>();
final HashMap<Integer, TLRPC.User> newResultsHashMap = new HashMap<>();
final HashMap<Integer, TLRPC.User> newMap = new HashMap<>();
if (!usernameOnly && needBotContext && dogPostion == 0 && !SearchQuery.inlineBots.isEmpty()) {
int count = 0;
for (int a = 0; a < SearchQuery.inlineBots.size(); a++) {
TLRPC.User user = MessagesController.getInstance().getUser(SearchQuery.inlineBots.get(a).peer.user_id);
if (user == null) {
continue;
}
if (user.username != null && user.username.length() > 0 && (usernameString.length() > 0 && user.username.toLowerCase().startsWith(usernameString) || usernameString.length() == 0)) {
newResult.add(user);
newResultsHashMap.put(user.id, user);
count++;
}
if (count == 5) {
break;
}
}
}
final TLRPC.Chat chat;
if (parentFragment != null) {
chat = parentFragment.getCurrentChat();
} else if (info != null) {
chat = MessagesController.getInstance().getChat(info.id);
} else {
chat = null;
}
if (chat != null && info != null && info.participants != null && (!ChatObject.isChannel(chat) || chat.megagroup)) {
for (int a = 0; a < info.participants.participants.size(); a++) {
TLRPC.ChatParticipant chatParticipant = info.participants.participants.get(a);
TLRPC.User user = MessagesController.getInstance().getUser(chatParticipant.user_id);
if (user == null || !usernameOnly && UserObject.isUserSelf(user) || newResultsHashMap.containsKey(user.id)) {
continue;
}
if (usernameString.length() == 0) {
if (!user.deleted && (allowNewMentions || !allowNewMentions && user.username != null && user.username.length() != 0)) {
newResult.add(user);
}
} else {
if (user.username != null && user.username.length() > 0 && user.username.toLowerCase().startsWith(usernameString)) {
newResult.add(user);
newMap.put(user.id, user);
} else {
if (!allowNewMentions && (user.username == null || user.username.length() == 0)) {
continue;
}
if (user.first_name != null && user.first_name.length() > 0 && user.first_name.toLowerCase().startsWith(usernameString)) {
newResult.add(user);
newMap.put(user.id, user);
} else if (user.last_name != null && user.last_name.length() > 0 && user.last_name.toLowerCase().startsWith(usernameString)) {
newResult.add(user);
newMap.put(user.id, user);
} else if (hasSpace && ContactsController.formatName(user.first_name, user.last_name).toLowerCase().startsWith(usernameString)) {
newResult.add(user);
newMap.put(user.id, user);
}
}
}
}
}
searchResultHashtags = null;
searchResultCommands = null;
searchResultCommandsHelp = null;
searchResultCommandsUsers = null;
searchResultSuggestions = null;
searchResultUsernames = newResult;
searchResultUsernamesMap = newMap;
if (chat != null && chat.megagroup && usernameString.length() > 0) {
AndroidUtilities.runOnUIThread(searchGlobalRunnable = new Runnable() {
@Override
public void run() {
if (searchGlobalRunnable != this) {
return;
}
TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants();
req.channel = MessagesController.getInputChannel(chat);
req.limit = 20;
req.offset = 0;
req.filter = new TLRPC.TL_channelParticipantsSearch();
req.filter.q = usernameString;
final int currentReqId = ++channelLastReqId;
channelReqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (channelReqId != 0 && currentReqId == channelLastReqId && searchResultUsernamesMap != null && searchResultUsernames != null) {
if (error == null) {
TLRPC.TL_channels_channelParticipants res = (TLRPC.TL_channels_channelParticipants) response;
MessagesController.getInstance().putUsers(res.users, false);
if (!res.participants.isEmpty()) {
int currentUserId = UserConfig.getClientUserId();
for (int a = 0; a < res.participants.size(); a++) {
TLRPC.ChannelParticipant participant = res.participants.get(a);
if (searchResultUsernamesMap.containsKey(participant.user_id) || !isSearchingMentions && participant.user_id == currentUserId) {
continue;
}
TLRPC.User user = MessagesController.getInstance().getUser(participant.user_id);
if (user == null) {
return;
}
searchResultUsernames.add(user);
}
notifyDataSetChanged();
}
}
}
channelReqId = 0;
}
});
}
});
}
}, 200);
}
Collections.sort(searchResultUsernames, new Comparator<TLRPC.User>() {
@Override
public int compare(TLRPC.User lhs, TLRPC.User rhs) {
if (newResultsHashMap.containsKey(lhs.id) && newResultsHashMap.containsKey(rhs.id)) {
return 0;
} else if (newResultsHashMap.containsKey(lhs.id)) {
return -1;
} else if (newResultsHashMap.containsKey(rhs.id)) {
return 1;
}
int lhsNum = users.indexOf(lhs.id);
int rhsNum = users.indexOf(rhs.id);
if (lhsNum != -1 && rhsNum != -1) {
return lhsNum < rhsNum ? -1 : (lhsNum == rhsNum ? 0 : 1);
} else if (lhsNum != -1 && rhsNum == -1) {
return -1;
} else if (lhsNum == -1 && rhsNum != -1) {
return 1;
}
return 0;
}
});
notifyDataSetChanged();
delegate.needChangePanelVisibility(!newResult.isEmpty());
} else if (foundType == 1) {
ArrayList<String> newResult = new ArrayList<>();
String hashtagString = result.toString().toLowerCase();
ArrayList<SearchAdapterHelper.HashtagObject> hashtags = searchAdapterHelper.getHashtags();
for (int a = 0; a < hashtags.size(); a++) {
SearchAdapterHelper.HashtagObject hashtagObject = hashtags.get(a);
if (hashtagObject != null && hashtagObject.hashtag != null && hashtagObject.hashtag.startsWith(hashtagString)) {
newResult.add(hashtagObject.hashtag);
}
}
searchResultHashtags = newResult;
searchResultUsernames = null;
searchResultUsernamesMap = null;
searchResultCommands = null;
searchResultCommandsHelp = null;
searchResultCommandsUsers = null;
searchResultSuggestions = null;
notifyDataSetChanged();
delegate.needChangePanelVisibility(!newResult.isEmpty());
} else if (foundType == 2) {
ArrayList<String> newResult = new ArrayList<>();
ArrayList<String> newResultHelp = new ArrayList<>();
ArrayList<TLRPC.User> newResultUsers = new ArrayList<>();
String command = result.toString().toLowerCase();
for (HashMap.Entry<Integer, TLRPC.BotInfo> entry : botInfo.entrySet()) {
TLRPC.BotInfo botInfo = entry.getValue();
for (int a = 0; a < botInfo.commands.size(); a++) {
TLRPC.TL_botCommand botCommand = botInfo.commands.get(a);
if (botCommand != null && botCommand.command != null && botCommand.command.startsWith(command)) {
newResult.add("/" + botCommand.command);
newResultHelp.add(botCommand.description);
newResultUsers.add(MessagesController.getInstance().getUser(botInfo.user_id));
}
}
}
searchResultHashtags = null;
searchResultUsernames = null;
searchResultUsernamesMap = null;
searchResultSuggestions = null;
searchResultCommands = newResult;
searchResultCommandsHelp = newResultHelp;
searchResultCommandsUsers = newResultUsers;
notifyDataSetChanged();
delegate.needChangePanelVisibility(!newResult.isEmpty());
} else if (foundType == 3) {
if (!hasIllegalUsernameCharacters) {
Object[] suggestions = Emoji.getSuggestion(result.toString());
if (suggestions != null) {
searchResultSuggestions = new ArrayList<>();
for (int a = 0; a < suggestions.length; a++) {
EmojiSuggestion suggestion = (EmojiSuggestion) suggestions[a];
suggestion.emoji = suggestion.emoji.replace("\ufe0f", "");
searchResultSuggestions.add(suggestion);
}
Emoji.loadRecentEmoji();
Collections.sort(searchResultSuggestions, new Comparator<EmojiSuggestion>() {
@Override
public int compare(EmojiSuggestion o1, EmojiSuggestion o2) {
Integer n1 = Emoji.emojiUseHistory.get(o1.emoji);
if (n1 == null) {
n1 = 0;
}
Integer n2 = Emoji.emojiUseHistory.get(o2.emoji);
if (n2 == null) {
n2 = 0;
}
return n2.compareTo(n1);
}
});
}
searchResultHashtags = null;
searchResultUsernames = null;
searchResultUsernamesMap = null;
searchResultCommands = null;
searchResultCommandsHelp = null;
searchResultCommandsUsers = null;
notifyDataSetChanged();
delegate.needChangePanelVisibility(searchResultSuggestions != null);
} else {
delegate.needChangePanelVisibility(false);
}
}
}
public int getResultStartPosition() {
return resultStartPosition;
}
public int getResultLength() {
return resultLength;
}
public ArrayList<TLRPC.BotInlineResult> getSearchResultBotContext() {
return searchResultBotContext;
}
@Override
public int getItemCount() {
if (foundContextBot != null && !inlineMediaEnabled) {
return 1;
}
if (searchResultBotContext != null) {
return searchResultBotContext.size() + (searchResultBotContextSwitch != null ? 1 : 0);
} else if (searchResultUsernames != null) {
return searchResultUsernames.size();
} else if (searchResultHashtags != null) {
return searchResultHashtags.size();
} else if (searchResultCommands != null) {
return searchResultCommands.size();
} else if (searchResultSuggestions != null) {
return searchResultSuggestions.size();
}
return 0;
}
@Override
public int getItemViewType(int position) {
if (foundContextBot != null && !inlineMediaEnabled) {
return 3;
} else if (searchResultBotContext != null) {
if (position == 0 && searchResultBotContextSwitch != null) {
return 2;
}
return 1;
} else {
return 0;
}
}
public void addHashtagsFromMessage(CharSequence message) {
searchAdapterHelper.addHashtagsFromMessage(message);
}
public int getItemPosition(int i) {
if (searchResultBotContext != null && searchResultBotContextSwitch != null) {
i--;
}
return i;
}
public Object getItem(int i) {
if (searchResultBotContext != null) {
if (searchResultBotContextSwitch != null) {
if (i == 0) {
return searchResultBotContextSwitch;
} else {
i--;
}
}
if (i < 0 || i >= searchResultBotContext.size()) {
return null;
}
return searchResultBotContext.get(i);
} else if (searchResultUsernames != null) {
if (i < 0 || i >= searchResultUsernames.size()) {
return null;
}
return searchResultUsernames.get(i);
} else if (searchResultHashtags != null) {
if (i < 0 || i >= searchResultHashtags.size()) {
return null;
}
return searchResultHashtags.get(i);
} else if (searchResultSuggestions != null) {
if (i < 0 || i >= searchResultSuggestions.size()) {
return null;
}
return searchResultSuggestions.get(i);
} else if (searchResultCommands != null) {
if (i < 0 || i >= searchResultCommands.size()) {
return null;
}
if (searchResultCommandsUsers != null && (botsCount != 1 || info instanceof TLRPC.TL_channelFull)) {
if (searchResultCommandsUsers.get(i) != null) {
return String.format("%s@%s", searchResultCommands.get(i), searchResultCommandsUsers.get(i) != null ? searchResultCommandsUsers.get(i).username : "");
} else {
return String.format("%s", searchResultCommands.get(i));
}
}
return searchResultCommands.get(i);
}
return null;
}
public boolean isLongClickEnabled() {
return searchResultHashtags != null || searchResultCommands != null;
}
public boolean isBotCommands() {
return searchResultCommands != null;
}
public boolean isBotContext() {
return searchResultBotContext != null;
}
public boolean isBannedInline() {
return foundContextBot != null && !inlineMediaEnabled;
}
public boolean isMediaLayout() {
return contextMedia;
}
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
return foundContextBot == null || inlineMediaEnabled;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case 0:
view = new MentionCell(mContext);
((MentionCell) view).setIsDarkTheme(isDarkTheme);
break;
case 1:
view = new ContextLinkCell(mContext);
((ContextLinkCell) view).setDelegate(new ContextLinkCell.ContextLinkCellDelegate() {
@Override
public void didPressedImage(ContextLinkCell cell) {
delegate.onContextClick(cell.getResult());
}
});
break;
case 2:
view = new BotSwitchCell(mContext);
break;
case 3:
default:
TextView textView = new TextView(mContext);
textView.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8));
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2));
view = textView;
break;
}
return new RecyclerListView.Holder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType() == 3) {
TextView textView = (TextView) holder.itemView;
TLRPC.Chat chat = parentFragment.getCurrentChat();
if (chat != null) {
if (AndroidUtilities.isBannedForever(chat.banned_rights.until_date)) {
textView.setText(LocaleController.getString("AttachInlineRestrictedForever", R.string.AttachInlineRestrictedForever));
} else {
textView.setText(LocaleController.formatString("AttachInlineRestricted", R.string.AttachInlineRestricted, LocaleController.formatDateForBan(chat.banned_rights.until_date)));
}
}
} else if (searchResultBotContext != null) {
boolean hasTop = searchResultBotContextSwitch != null;
if (holder.getItemViewType() == 2) {
if (hasTop) {
((BotSwitchCell) holder.itemView).setText(searchResultBotContextSwitch.text);
}
} else {
if (hasTop) {
position--;
}
((ContextLinkCell) holder.itemView).setLink(searchResultBotContext.get(position), contextMedia, position != searchResultBotContext.size() - 1, hasTop && position == 0);
}
} else {
if (searchResultUsernames != null) {
((MentionCell) holder.itemView).setUser(searchResultUsernames.get(position));
} else if (searchResultHashtags != null) {
((MentionCell) holder.itemView).setText(searchResultHashtags.get(position));
} else if (searchResultSuggestions != null) {
((MentionCell) holder.itemView).setEmojiSuggestion(searchResultSuggestions.get(position));
} else if (searchResultCommands != null) {
((MentionCell) holder.itemView).setBotCommand(searchResultCommands.get(position), searchResultCommandsHelp.get(position), searchResultCommandsUsers != null ? searchResultCommandsUsers.get(position) : null);
}
}
}
public void onRequestPermissionsResultFragment(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 2) {
if (foundContextBot != null && foundContextBot.bot_inline_geo) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationProvider.start();
} else {
onLocationUnavailable();
}
}
}
}
}
| gpl-2.0 |
jeffgdotorg/opennms | core/jmx/api/src/main/java/org/opennms/netmgt/jmx/connection/JmxServerConnectionException.java | 2182 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.jmx.connection;
import java.io.IOException;
/**
* Is used to indicate that a connection to a JMX Server (MBeanServer) could not be established.
* The reason may be that the server is not reachable, or credentials are invalid or
* there is no {@link org.opennms.netmgt.jmx.connection.JmxServerConnector} registered
* for the {@link org.opennms.netmgt.jmx.connection.JmxConnectors}.
* <p/>
* The exception's <code>errorMessage</code> should provide details about the concrete error.
*/
public class JmxServerConnectionException extends Exception {
private static final long serialVersionUID = 1L;
public JmxServerConnectionException(final String errorMessage) {
super(errorMessage);
}
public JmxServerConnectionException(final IOException ioException) {
super(ioException);
}
public JmxServerConnectionException(String errorMessage, Exception exception) {
super(errorMessage, exception);
}
}
| gpl-2.0 |
md-5/jdk10 | src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java | 14042 | /*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security;
import java.io.InputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.List;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver;
import com.sun.org.apache.xml.internal.security.transforms.Transform;
import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
import com.sun.org.apache.xml.internal.security.utils.I18n;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* This class does the configuration of the library. This includes creating
* the mapping of Canonicalization and Transform algorithms. Initialization is
* done by calling {@link Init#init} which should be done in any static block
* of the files of this library. We ensure that this call is only executed once.
*/
public class Init {
/** The namespace for CONF file **/
public static final String CONF_NS = "http://www.xmlsecurity.org/NS/#configuration";
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(Init.class);
/** Field alreadyInitialized */
private static boolean alreadyInitialized = false;
/**
* Method isInitialized
* @return true if the library is already initialized.
*/
public static final synchronized boolean isInitialized() {
return Init.alreadyInitialized;
}
/**
* Method init
*
*/
public static synchronized void init() {
if (alreadyInitialized) {
return;
}
InputStream is =
AccessController.doPrivileged(
(PrivilegedAction<InputStream>)
() -> {
String cfile =
System.getProperty("com.sun.org.apache.xml.internal.security.resource.config");
if (cfile == null) {
return null;
}
return Init.class.getResourceAsStream(cfile);
}
);
if (is == null) {
dynamicInit();
} else {
fileInit(is);
}
alreadyInitialized = true;
}
/**
* Dynamically initialise the library by registering the default algorithms/implementations
*/
private static void dynamicInit() {
//
// Load the Resource Bundle - the default is the English resource bundle.
// To load another resource bundle, call I18n.init(...) before calling this
// method.
//
I18n.init("en", "US");
LOG.debug("Registering default algorithms");
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>(){
@Override public Void run() throws XMLSecurityException {
//
// Bind the default prefixes
//
ElementProxy.registerDefaultPrefixes();
//
// Set the default Transforms
//
Transform.registerDefaultAlgorithms();
//
// Set the default signature algorithms
//
SignatureAlgorithm.registerDefaultAlgorithms();
//
// Set the default JCE algorithms
//
JCEMapper.registerDefaultAlgorithms();
//
// Set the default c14n algorithms
//
Canonicalizer.registerDefaultAlgorithms();
//
// Register the default resolvers
//
ResourceResolver.registerDefaultResolvers();
//
// Register the default key resolvers
//
KeyResolver.registerDefaultResolvers();
return null;
}
});
} catch (PrivilegedActionException ex) {
XMLSecurityException xse = (XMLSecurityException)ex.getException();
LOG.error(xse.getMessage(), xse);
xse.printStackTrace();
}
}
/**
* Initialise the library from a configuration file
*/
private static void fileInit(InputStream is) {
try {
/* read library configuration file */
Document doc = XMLUtils.read(is, false);
Node config = doc.getFirstChild();
for (; config != null; config = config.getNextSibling()) {
if ("Configuration".equals(config.getLocalName())) {
break;
}
}
if (config == null) {
LOG.error("Error in reading configuration file - Configuration element not found");
return;
}
for (Node el = config.getFirstChild(); el != null; el = el.getNextSibling()) {
if (Node.ELEMENT_NODE != el.getNodeType()) {
continue;
}
String tag = el.getLocalName();
if ("ResourceBundles".equals(tag)) {
Element resource = (Element)el;
/* configure internationalization */
Attr langAttr = resource.getAttributeNodeNS(null, "defaultLanguageCode");
Attr countryAttr = resource.getAttributeNodeNS(null, "defaultCountryCode");
String languageCode =
(langAttr == null) ? null : langAttr.getNodeValue();
String countryCode =
(countryAttr == null) ? null : countryAttr.getNodeValue();
I18n.init(languageCode, countryCode);
}
if ("CanonicalizationMethods".equals(tag)) {
Element[] list =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "CanonicalizationMethod");
for (Element element : list) {
String uri = element.getAttributeNS(null, "URI");
String javaClass =
element.getAttributeNS(null, "JAVACLASS");
try {
Canonicalizer.register(uri, javaClass);
LOG.debug("Canonicalizer.register({}, {})", uri, javaClass);
} catch (ClassNotFoundException e) {
Object exArgs[] = { uri, javaClass };
LOG.error(I18n.translate("algorithm.classDoesNotExist", exArgs));
}
}
}
if ("TransformAlgorithms".equals(tag)) {
Element[] tranElem =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "TransformAlgorithm");
for (Element element : tranElem) {
String uri = element.getAttributeNS(null, "URI");
String javaClass =
element.getAttributeNS(null, "JAVACLASS");
try {
Transform.register(uri, javaClass);
LOG.debug("Transform.register({}, {})", uri, javaClass);
} catch (ClassNotFoundException e) {
Object exArgs[] = { uri, javaClass };
LOG.error(I18n.translate("algorithm.classDoesNotExist", exArgs));
} catch (NoClassDefFoundError ex) {
LOG.warn("Not able to found dependencies for algorithm, I'll keep working.");
}
}
}
if ("JCEAlgorithmMappings".equals(tag)) {
Node algorithmsNode = ((Element)el).getElementsByTagName("Algorithms").item(0);
if (algorithmsNode != null) {
Element[] algorithms =
XMLUtils.selectNodes(algorithmsNode.getFirstChild(), CONF_NS, "Algorithm");
for (Element element : algorithms) {
String id = element.getAttributeNS(null, "URI");
JCEMapper.register(id, new JCEMapper.Algorithm(element));
}
}
}
if ("SignatureAlgorithms".equals(tag)) {
Element[] sigElems =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "SignatureAlgorithm");
for (Element sigElem : sigElems) {
String uri = sigElem.getAttributeNS(null, "URI");
String javaClass =
sigElem.getAttributeNS(null, "JAVACLASS");
/** $todo$ handle registering */
try {
SignatureAlgorithm.register(uri, javaClass);
LOG.debug("SignatureAlgorithm.register({}, {})", uri, javaClass);
} catch (ClassNotFoundException e) {
Object exArgs[] = { uri, javaClass };
LOG.error(I18n.translate("algorithm.classDoesNotExist", exArgs));
}
}
}
if ("ResourceResolvers".equals(tag)) {
Element[] resolverElem =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver");
for (Element element : resolverElem) {
String javaClass =
element.getAttributeNS(null, "JAVACLASS");
String description =
element.getAttributeNS(null, "DESCRIPTION");
if (description != null && description.length() > 0) {
LOG.debug("Register Resolver: {}: {}", javaClass, description);
} else {
LOG.debug("Register Resolver: {}: For unknown purposes", javaClass);
}
try {
ResourceResolver.register(javaClass);
} catch (Throwable e) {
LOG.warn(
"Cannot register:" + javaClass
+ " perhaps some needed jars are not installed",
e
);
}
}
}
if ("KeyResolver".equals(tag)){
Element[] resolverElem =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver");
List<String> classNames = new ArrayList<>(resolverElem.length);
for (Element element : resolverElem) {
String javaClass =
element.getAttributeNS(null, "JAVACLASS");
String description =
element.getAttributeNS(null, "DESCRIPTION");
if (description != null && description.length() > 0) {
LOG.debug("Register Resolver: {}: {}", javaClass, description);
} else {
LOG.debug("Register Resolver: {}: For unknown purposes", javaClass);
}
classNames.add(javaClass);
}
KeyResolver.registerClassNames(classNames);
}
if ("PrefixMappings".equals(tag)){
LOG.debug("Now I try to bind prefixes:");
Element[] nl =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "PrefixMapping");
for (Element element : nl) {
String namespace = element.getAttributeNS(null, "namespace");
String prefix = element.getAttributeNS(null, "prefix");
LOG.debug("Now I try to bind {} to {}", prefix, namespace);
ElementProxy.setDefaultPrefix(namespace, prefix);
}
}
}
} catch (Exception e) {
LOG.error("Bad: ", e);
}
}
}
| gpl-2.0 |
person594/cs153 | assignment4/wci/backend/interpreter/executors/SelectExecutor.java | 3470 | /**
* <h1>SelectExecutor</h1>
*
* <p>Execute a SELECT statement. Optimized.</p>
*
* <p>Copyright (c) 2009 by Ronald Mak</p>
* <p>For instructional purposes only. No warranties.</p>
*/
package wci.backend.interpreter.executors;
import java.util.ArrayList;
import java.util.HashMap;
import wci.intermediate.*;
import wci.backend.interpreter.*;
import static wci.intermediate.icodeimpl.ICodeNodeTypeImpl.*;
import static wci.intermediate.icodeimpl.ICodeKeyImpl.*;
import static wci.backend.interpreter.RuntimeErrorCode.*;
public class SelectExecutor extends StatementExecutor
{
/**
* Constructor.
* @param the parent executor.
*/
public SelectExecutor(Executor parent)
{
super(parent);
}
// Jump table cache: entry key is a SELECT node,
// entry value is the jump table.
// Jump table: entry key is a selection value,
// entry value is the branch statement.
private static HashMap<ICodeNode, HashMap<Object, ICodeNode>> jumpCache =
new HashMap<ICodeNode, HashMap<Object, ICodeNode>>();
/**
* Execute SELECT statement.
* @param node the root node of the statement.
* @return null.
*/
public Object execute(ICodeNode node)
{
// Is there already an entry for this SELECT node in the
// jump table cache? If not, create a jump table entry.
HashMap<Object, ICodeNode> jumpTable = jumpCache.get(node);
if (jumpTable == null) {
jumpTable = createJumpTable(node);
jumpCache.put(node, jumpTable);
}
// Get the SELECT node's children.
ArrayList<ICodeNode> selectChildren = node.getChildren();
ICodeNode exprNode = selectChildren.get(0);
// Evaluate the SELECT expression.
ExpressionExecutor expressionExecutor = new ExpressionExecutor(this);
Object selectValue = expressionExecutor.execute(exprNode);
// If there is a selection, execute the SELECT_BRANCH's statement.
ICodeNode statementNode = jumpTable.get(selectValue);
if (statementNode != null) {
StatementExecutor statementExecutor = new StatementExecutor(this);
statementExecutor.execute(statementNode);
}
++executionCount; // count the SELECT statement itself
return null;
}
/**
* Create a jump table for a SELECT node.
* @param node the SELECT node.
* @return the jump table.
*/
private HashMap<Object, ICodeNode> createJumpTable(ICodeNode node)
{
HashMap<Object, ICodeNode> jumpTable = new HashMap<Object, ICodeNode>();
// Loop over children that are SELECT_BRANCH nodes.
ArrayList<ICodeNode> selectChildren = node.getChildren();
for (int i = 1; i < selectChildren.size(); ++i) {
ICodeNode branchNode = selectChildren.get(i);
ICodeNode constantsNode = branchNode.getChildren().get(0);
ICodeNode statementNode = branchNode.getChildren().get(1);
// Loop over the constants children of the branch's CONSTANTS_NODE.
ArrayList<ICodeNode> constantsList = constantsNode.getChildren();
for (ICodeNode constantNode : constantsList) {
// Create a jump table entry.
Object value = constantNode.getAttribute(VALUE);
jumpTable.put(value, statementNode);
}
}
return jumpTable;
}
}
| gpl-2.0 |
RangerRick/opennms | opennms-dao/src/main/java/org/opennms/netmgt/dao/CollectorConfigDao.java | 2175 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.dao;
import java.util.Collection;
import org.opennms.netmgt.config.CollectdPackage;
import org.opennms.netmgt.config.collectd.Collector;
/**
* <p>CollectorConfigDao interface.</p>
*/
public interface CollectorConfigDao {
/**
* <p>getSchedulerThreads</p>
*
* @return a int.
*/
int getSchedulerThreads();
/**
* <p>getCollectors</p>
*
* @return a {@link java.util.Collection} object.
*/
Collection<Collector> getCollectors();
/**
* <p>rebuildPackageIpListMap</p>
*/
void rebuildPackageIpListMap();
/**
* <p>getPackages</p>
*
* @return a {@link java.util.Collection} object.
*/
Collection<CollectdPackage> getPackages();
/**
* <p>getPackage</p>
*
* @param name a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.config.CollectdPackage} object.
*/
CollectdPackage getPackage(String name);
}
| gpl-2.0 |
arodchen/MaxSim | graal/agent/src/share/classes/sun/jvm/hotspot/ci/ciEnv.java | 3973 | /*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
package sun.jvm.hotspot.ci;
import java.io.PrintStream;
import java.util.*;
import sun.jvm.hotspot.debugger.*;
import sun.jvm.hotspot.runtime.*;
import sun.jvm.hotspot.oops.*;
import sun.jvm.hotspot.opto.*;
import sun.jvm.hotspot.compiler.CompileTask;
import sun.jvm.hotspot.prims.JvmtiExport;
import sun.jvm.hotspot.types.*;
import sun.jvm.hotspot.utilities.GrowableArray;
public class ciEnv extends VMObject {
static {
VM.registerVMInitializedObserver(new Observer() {
public void update(Observable o, Object data) {
initialize(VM.getVM().getTypeDataBase());
}
});
}
private static synchronized void initialize(TypeDataBase db) throws WrongTypeException {
Type type = db.lookupType("ciEnv");
dependenciesField = type.getAddressField("_dependencies");
factoryField = type.getAddressField("_factory");
compilerDataField = type.getAddressField("_compiler_data");
taskField = type.getAddressField("_task");
systemDictionaryModificationCounterField = new CIntField(type.getCIntegerField("_system_dictionary_modification_counter"), 0);
}
private static AddressField dependenciesField;
private static AddressField factoryField;
private static AddressField compilerDataField;
private static AddressField taskField;
private static CIntField systemDictionaryModificationCounterField;
public ciEnv(Address addr) {
super(addr);
}
public Compile compilerData() {
return new Compile(compilerDataField.getValue(this.getAddress()));
}
public ciObjectFactory factory() {
return new ciObjectFactory(factoryField.getValue(this.getAddress()));
}
public CompileTask task() {
return new CompileTask(taskField.getValue(this.getAddress()));
}
public void dumpReplayData(PrintStream out) {
out.println("JvmtiExport can_access_local_variables " +
(JvmtiExport.canAccessLocalVariables() ? '1' : '0'));
out.println("JvmtiExport can_hotswap_or_post_breakpoint " +
(JvmtiExport.canHotswapOrPostBreakpoint() ? '1' : '0'));
out.println("JvmtiExport can_post_on_exceptions " +
(JvmtiExport.canPostOnExceptions() ? '1' : '0'));
GrowableArray<ciMetadata> objects = factory().objects();
out.println("# " + objects.length() + " ciObject found");
for (int i = 0; i < objects.length(); i++) {
ciMetadata o = objects.at(i);
out.println("# ciMetadata" + i + " @ " + o);
o.dumpReplayData(out);
}
CompileTask task = task();
Method method = task.method();
int entryBci = task.osrBci();
int compLevel = task.compLevel();
Klass holder = method.getMethodHolder();
out.println("compile " + holder.getName().asString() + " " +
OopUtilities.escapeString(method.getName().asString()) + " " +
method.getSignature().asString() + " " +
entryBci + " " + compLevel);
}
}
| gpl-2.0 |
juliocamarero/jukebox | sdk/portlets/jukebox-portlet/docroot/WEB-INF/src/org/liferay/jukebox/search/SongSearchTerms.java | 1252 | /**
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* 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.
*/
package org.liferay.jukebox.search;
import com.liferay.portal.kernel.dao.search.DAOParamUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import javax.portlet.PortletRequest;
/**
* @author Eudaldo Alonso
*/
public class SongSearchTerms extends SongDisplayTerms {
public SongSearchTerms(PortletRequest portletRequest) {
super(portletRequest);
album = DAOParamUtil.getString(portletRequest, ALBUM);
artist = DAOParamUtil.getString(portletRequest, ARTIST);
groupId = ParamUtil.getLong(portletRequest, GROUP_ID);
title = DAOParamUtil.getString(portletRequest, TITLE);
}
public void setGroupId(long groupId) {
this.groupId = groupId;
}
} | gpl-2.0 |
LoickBriot/replication-benchmarker | src/main/java/jbenchmarker/sim/PlaceboFactory.java | 2945 | /**
* Replication Benchmarker
* https://github.com/score-team/replication-benchmarker/ Copyright (C) 2013
* LORIA / Inria / SCORE Team
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jbenchmarker.sim;
import crdt.CRDT;
import crdt.Operation;
import crdt.simulator.IncorrectTraceException;
import java.util.List;
import jbenchmarker.core.*;
/**
* Used to measure the base memory/time required to simulate a trace.
*
* @author urso
*/
public class PlaceboFactory extends ReplicaFactory {
public static class PlaceboOperation implements Operation {
public PlaceboOperation() {
}
@Override
public Operation clone() {
return new PlaceboOperation();
}
}
public static class PlaceboDocument implements Document {
@Override
public String view() {
return "";
}
@Override
public void apply(Operation op) {
}
@Override
public int viewLength() {
return 0;
}
}
private static class PlaceboMerge extends MergeAlgorithm {
PlaceboMerge() {
super(new PlaceboDocument(), 0);
}
@Override
protected void integrateRemote(crdt.Operation message) throws IncorrectTraceException {
this.getDoc().apply(message);
}
protected List<Operation> generateLocal(SequenceOperation opt) throws IncorrectTraceException {
int nbop = (opt.getType() == SequenceOperation.OpType.delete) ? opt.getLenghOfADel() : opt.getContent().size();
List<Operation> l = new java.util.ArrayList<Operation>(nbop);
for (int i = 0; i < nbop; i++) {
l.add(new PlaceboOperation());
}
return l;
}
@Override
public CRDT<String> create() {
return new PlaceboMerge();
}
@Override
protected List<Operation> localInsert(SequenceOperation opt) throws IncorrectTraceException {
return generateLocal(opt);
}
@Override
protected List<Operation> localDelete(SequenceOperation opt) throws IncorrectTraceException {
return generateLocal(opt);
}
}
@Override
public MergeAlgorithm create(int r) {
return new PlaceboMerge();
}
}
| gpl-3.0 |
jinsedeyuzhou/NewsClient | viewanimations/src/main/java/com/daimajia/androidanimations/library/flippers/FlipOutXAnimator.java | 1633 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 daimajia
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.daimajia.androidanimations.library.flippers;
import android.animation.ObjectAnimator;
import android.view.View;
import com.daimajia.androidanimations.library.BaseViewAnimator;
public class FlipOutXAnimator extends BaseViewAnimator {
@Override
public void prepare(View target) {
getAnimatorAgent().playTogether(
ObjectAnimator.ofFloat(target, "rotationX", 0, 90),
ObjectAnimator.ofFloat(target, "alpha", 1, 0)
);
}
}
| gpl-3.0 |
joyghosh/hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/snapshot/FSImageFormatPBSnapshot.java | 24905 | /**
* 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.hdfs.server.namenode.snapshot;
import static org.apache.hadoop.hdfs.server.namenode.FSImageFormatPBINode.Loader.loadINodeDirectory;
import static org.apache.hadoop.hdfs.server.namenode.FSImageFormatPBINode.Loader.loadPermission;
import static org.apache.hadoop.hdfs.server.namenode.FSImageFormatPBINode.Loader.updateBlocksMap;
import static org.apache.hadoop.hdfs.server.namenode.FSImageFormatPBINode.Saver.buildINodeDirectory;
import static org.apache.hadoop.hdfs.server.namenode.FSImageFormatPBINode.Saver.buildINodeFile;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.google.common.collect.ImmutableList;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.fs.permission.PermissionStatus;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.BlockProto;
import org.apache.hadoop.hdfs.protocolPB.PBHelper;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfoContiguous;
import org.apache.hadoop.hdfs.server.namenode.AclEntryStatusFormat;
import org.apache.hadoop.hdfs.server.namenode.AclFeature;
import org.apache.hadoop.hdfs.server.namenode.FSDirectory;
import org.apache.hadoop.hdfs.server.namenode.FSImageFormatPBINode;
import org.apache.hadoop.hdfs.server.namenode.FSImageFormatProtobuf;
import org.apache.hadoop.hdfs.server.namenode.FSImageFormatProtobuf.LoaderContext;
import org.apache.hadoop.hdfs.server.namenode.FSImageFormatProtobuf.SectionName;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.FileSummary;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.INodeReferenceSection;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.INodeSection;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.SnapshotDiffSection;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.SnapshotDiffSection.CreatedListEntry;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.SnapshotDiffSection.DiffEntry.Type;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.SnapshotSection;
import org.apache.hadoop.hdfs.server.namenode.INode;
import org.apache.hadoop.hdfs.server.namenode.INodeDirectory;
import org.apache.hadoop.hdfs.server.namenode.INodeDirectoryAttributes;
import org.apache.hadoop.hdfs.server.namenode.INodeFile;
import org.apache.hadoop.hdfs.server.namenode.INodeFileAttributes;
import org.apache.hadoop.hdfs.server.namenode.INodeMap;
import org.apache.hadoop.hdfs.server.namenode.INodeReference;
import org.apache.hadoop.hdfs.server.namenode.INodeReference.DstReference;
import org.apache.hadoop.hdfs.server.namenode.INodeReference.WithCount;
import org.apache.hadoop.hdfs.server.namenode.INodeReference.WithName;
import org.apache.hadoop.hdfs.server.namenode.INodeWithAdditionalFields;
import org.apache.hadoop.hdfs.server.namenode.QuotaByStorageTypeEntry;
import org.apache.hadoop.hdfs.server.namenode.SaveNamespaceContext;
import org.apache.hadoop.hdfs.server.namenode.snapshot.DirectoryWithSnapshotFeature.DirectoryDiff;
import org.apache.hadoop.hdfs.server.namenode.snapshot.DirectoryWithSnapshotFeature.DirectoryDiffList;
import org.apache.hadoop.hdfs.server.namenode.snapshot.Snapshot.Root;
import org.apache.hadoop.hdfs.server.namenode.XAttrFeature;
import org.apache.hadoop.hdfs.util.Diff.ListType;
import org.apache.hadoop.hdfs.util.EnumCounters;
import com.google.common.base.Preconditions;
import com.google.protobuf.ByteString;
@InterfaceAudience.Private
public class FSImageFormatPBSnapshot {
/**
* Loading snapshot related information from protobuf based FSImage
*/
public final static class Loader {
private final FSNamesystem fsn;
private final FSDirectory fsDir;
private final FSImageFormatProtobuf.Loader parent;
private final Map<Integer, Snapshot> snapshotMap;
public Loader(FSNamesystem fsn, FSImageFormatProtobuf.Loader parent) {
this.fsn = fsn;
this.fsDir = fsn.getFSDirectory();
this.snapshotMap = new HashMap<Integer, Snapshot>();
this.parent = parent;
}
/**
* The sequence of the ref node in refList must be strictly the same with
* the sequence in fsimage
*/
public void loadINodeReferenceSection(InputStream in) throws IOException {
final List<INodeReference> refList = parent.getLoaderContext()
.getRefList();
while (true) {
INodeReferenceSection.INodeReference e = INodeReferenceSection
.INodeReference.parseDelimitedFrom(in);
if (e == null) {
break;
}
INodeReference ref = loadINodeReference(e);
refList.add(ref);
}
}
private INodeReference loadINodeReference(
INodeReferenceSection.INodeReference r) throws IOException {
long referredId = r.getReferredId();
INode referred = fsDir.getInode(referredId);
WithCount withCount = (WithCount) referred.getParentReference();
if (withCount == null) {
withCount = new INodeReference.WithCount(null, referred);
}
final INodeReference ref;
if (r.hasDstSnapshotId()) { // DstReference
ref = new INodeReference.DstReference(null, withCount,
r.getDstSnapshotId());
} else {
ref = new INodeReference.WithName(null, withCount, r.getName()
.toByteArray(), r.getLastSnapshotId());
}
return ref;
}
/**
* Load the snapshots section from fsimage. Also add snapshottable feature
* to snapshottable directories.
*/
public void loadSnapshotSection(InputStream in) throws IOException {
SnapshotManager sm = fsn.getSnapshotManager();
SnapshotSection section = SnapshotSection.parseDelimitedFrom(in);
int snum = section.getNumSnapshots();
sm.setNumSnapshots(snum);
sm.setSnapshotCounter(section.getSnapshotCounter());
for (long sdirId : section.getSnapshottableDirList()) {
INodeDirectory dir = fsDir.getInode(sdirId).asDirectory();
if (!dir.isSnapshottable()) {
dir.addSnapshottableFeature();
} else {
// dir is root, and admin set root to snapshottable before
dir.setSnapshotQuota(DirectorySnapshottableFeature.SNAPSHOT_LIMIT);
}
sm.addSnapshottable(dir);
}
loadSnapshots(in, snum);
}
private void loadSnapshots(InputStream in, int size) throws IOException {
for (int i = 0; i < size; i++) {
SnapshotSection.Snapshot pbs = SnapshotSection.Snapshot
.parseDelimitedFrom(in);
INodeDirectory root = loadINodeDirectory(pbs.getRoot(),
parent.getLoaderContext());
int sid = pbs.getSnapshotId();
INodeDirectory parent = fsDir.getInode(root.getId()).asDirectory();
Snapshot snapshot = new Snapshot(sid, root, parent);
// add the snapshot to parent, since we follow the sequence of
// snapshotsByNames when saving, we do not need to sort when loading
parent.getDirectorySnapshottableFeature().addSnapshot(snapshot);
snapshotMap.put(sid, snapshot);
}
}
/**
* Load the snapshot diff section from fsimage.
*/
public void loadSnapshotDiffSection(InputStream in) throws IOException {
final List<INodeReference> refList = parent.getLoaderContext()
.getRefList();
while (true) {
SnapshotDiffSection.DiffEntry entry = SnapshotDiffSection.DiffEntry
.parseDelimitedFrom(in);
if (entry == null) {
break;
}
long inodeId = entry.getInodeId();
INode inode = fsDir.getInode(inodeId);
SnapshotDiffSection.DiffEntry.Type type = entry.getType();
switch (type) {
case FILEDIFF:
loadFileDiffList(in, inode.asFile(), entry.getNumOfDiff());
break;
case DIRECTORYDIFF:
loadDirectoryDiffList(in, inode.asDirectory(), entry.getNumOfDiff(),
refList);
break;
}
}
}
/** Load FileDiff list for a file with snapshot feature */
private void loadFileDiffList(InputStream in, INodeFile file, int size)
throws IOException {
final FileDiffList diffs = new FileDiffList();
final LoaderContext state = parent.getLoaderContext();
for (int i = 0; i < size; i++) {
SnapshotDiffSection.FileDiff pbf = SnapshotDiffSection.FileDiff
.parseDelimitedFrom(in);
INodeFileAttributes copy = null;
if (pbf.hasSnapshotCopy()) {
INodeSection.INodeFile fileInPb = pbf.getSnapshotCopy();
PermissionStatus permission = loadPermission(
fileInPb.getPermission(), state.getStringTable());
AclFeature acl = null;
if (fileInPb.hasAcl()) {
int[] entries = AclEntryStatusFormat
.toInt(FSImageFormatPBINode.Loader.loadAclEntries(
fileInPb.getAcl(), state.getStringTable()));
acl = new AclFeature(entries);
}
XAttrFeature xAttrs = null;
if (fileInPb.hasXAttrs()) {
xAttrs = new XAttrFeature(FSImageFormatPBINode.Loader.loadXAttrs(
fileInPb.getXAttrs(), state.getStringTable()));
}
copy = new INodeFileAttributes.SnapshotCopy(pbf.getName()
.toByteArray(), permission, acl, fileInPb.getModificationTime(),
fileInPb.getAccessTime(), (short) fileInPb.getReplication(),
fileInPb.getPreferredBlockSize(),
(byte)fileInPb.getStoragePolicyID(),
xAttrs);
}
FileDiff diff = new FileDiff(pbf.getSnapshotId(), copy, null,
pbf.getFileSize());
List<BlockProto> bpl = pbf.getBlocksList();
BlockInfo[] blocks = new BlockInfo[bpl.size()];
for(int j = 0, e = bpl.size(); j < e; ++j) {
Block blk = PBHelper.convert(bpl.get(j));
BlockInfo storedBlock = fsn.getBlockManager().getStoredBlock(blk);
if(storedBlock == null) {
storedBlock = fsn.getBlockManager().addBlockCollection(
new BlockInfoContiguous(blk, copy.getFileReplication()), file);
}
blocks[j] = storedBlock;
}
if(blocks.length > 0) {
diff.setBlocks(blocks);
}
diffs.addFirst(diff);
}
file.addSnapshotFeature(diffs);
}
/** Load the created list in a DirectoryDiff */
private List<INode> loadCreatedList(InputStream in, INodeDirectory dir,
int size) throws IOException {
List<INode> clist = new ArrayList<INode>(size);
for (long c = 0; c < size; c++) {
CreatedListEntry entry = CreatedListEntry.parseDelimitedFrom(in);
INode created = SnapshotFSImageFormat.loadCreated(entry.getName()
.toByteArray(), dir);
clist.add(created);
}
return clist;
}
private void addToDeletedList(INode dnode, INodeDirectory parent) {
dnode.setParent(parent);
if (dnode.isFile()) {
updateBlocksMap(dnode.asFile(), fsn.getBlockManager());
}
}
/**
* Load the deleted list in a DirectoryDiff
*/
private List<INode> loadDeletedList(final List<INodeReference> refList,
InputStream in, INodeDirectory dir, List<Long> deletedNodes,
List<Integer> deletedRefNodes)
throws IOException {
List<INode> dlist = new ArrayList<INode>(deletedRefNodes.size()
+ deletedNodes.size());
// load non-reference inodes
for (long deletedId : deletedNodes) {
INode deleted = fsDir.getInode(deletedId);
dlist.add(deleted);
addToDeletedList(deleted, dir);
}
// load reference nodes in the deleted list
for (int refId : deletedRefNodes) {
INodeReference deletedRef = refList.get(refId);
dlist.add(deletedRef);
addToDeletedList(deletedRef, dir);
}
Collections.sort(dlist, new Comparator<INode>() {
@Override
public int compare(INode n1, INode n2) {
return n1.compareTo(n2.getLocalNameBytes());
}
});
return dlist;
}
/** Load DirectoryDiff list for a directory with snapshot feature */
private void loadDirectoryDiffList(InputStream in, INodeDirectory dir,
int size, final List<INodeReference> refList) throws IOException {
if (!dir.isWithSnapshot()) {
dir.addSnapshotFeature(null);
}
DirectoryDiffList diffs = dir.getDiffs();
final LoaderContext state = parent.getLoaderContext();
for (int i = 0; i < size; i++) {
// load a directory diff
SnapshotDiffSection.DirectoryDiff diffInPb = SnapshotDiffSection.
DirectoryDiff.parseDelimitedFrom(in);
final int snapshotId = diffInPb.getSnapshotId();
final Snapshot snapshot = snapshotMap.get(snapshotId);
int childrenSize = diffInPb.getChildrenSize();
boolean useRoot = diffInPb.getIsSnapshotRoot();
INodeDirectoryAttributes copy = null;
if (useRoot) {
copy = snapshot.getRoot();
} else if (diffInPb.hasSnapshotCopy()) {
INodeSection.INodeDirectory dirCopyInPb = diffInPb.getSnapshotCopy();
final byte[] name = diffInPb.getName().toByteArray();
PermissionStatus permission = loadPermission(
dirCopyInPb.getPermission(), state.getStringTable());
AclFeature acl = null;
if (dirCopyInPb.hasAcl()) {
int[] entries = AclEntryStatusFormat
.toInt(FSImageFormatPBINode.Loader.loadAclEntries(
dirCopyInPb.getAcl(), state.getStringTable()));
acl = new AclFeature(entries);
}
XAttrFeature xAttrs = null;
if (dirCopyInPb.hasXAttrs()) {
xAttrs = new XAttrFeature(FSImageFormatPBINode.Loader.loadXAttrs(
dirCopyInPb.getXAttrs(), state.getStringTable()));
}
long modTime = dirCopyInPb.getModificationTime();
boolean noQuota = dirCopyInPb.getNsQuota() == -1
&& dirCopyInPb.getDsQuota() == -1
&& (!dirCopyInPb.hasTypeQuotas());
if (noQuota) {
copy = new INodeDirectoryAttributes.SnapshotCopy(name,
permission, acl, modTime, xAttrs);
} else {
EnumCounters<StorageType> typeQuotas = null;
if (dirCopyInPb.hasTypeQuotas()) {
ImmutableList<QuotaByStorageTypeEntry> qes =
FSImageFormatPBINode.Loader.loadQuotaByStorageTypeEntries(
dirCopyInPb.getTypeQuotas());
typeQuotas = new EnumCounters<StorageType>(StorageType.class,
HdfsConstants.QUOTA_RESET);
for (QuotaByStorageTypeEntry qe : qes) {
if (qe.getQuota() >= 0 && qe.getStorageType() != null &&
qe.getStorageType().supportTypeQuota()) {
typeQuotas.set(qe.getStorageType(), qe.getQuota());
}
}
}
copy = new INodeDirectoryAttributes.CopyWithQuota(name, permission,
acl, modTime, dirCopyInPb.getNsQuota(),
dirCopyInPb.getDsQuota(), typeQuotas, xAttrs);
}
}
// load created list
List<INode> clist = loadCreatedList(in, dir,
diffInPb.getCreatedListSize());
// load deleted list
List<INode> dlist = loadDeletedList(refList, in, dir,
diffInPb.getDeletedINodeList(), diffInPb.getDeletedINodeRefList());
// create the directory diff
DirectoryDiff diff = new DirectoryDiff(snapshotId, copy, null,
childrenSize, clist, dlist, useRoot);
diffs.addFirst(diff);
}
}
}
/**
* Saving snapshot related information to protobuf based FSImage
*/
public final static class Saver {
private final FSNamesystem fsn;
private final FileSummary.Builder headers;
private final FSImageFormatProtobuf.Saver parent;
private final SaveNamespaceContext context;
public Saver(FSImageFormatProtobuf.Saver parent,
FileSummary.Builder headers, SaveNamespaceContext context,
FSNamesystem fsn) {
this.parent = parent;
this.headers = headers;
this.context = context;
this.fsn = fsn;
}
/**
* save all the snapshottable directories and snapshots to fsimage
*/
public void serializeSnapshotSection(OutputStream out) throws IOException {
SnapshotManager sm = fsn.getSnapshotManager();
SnapshotSection.Builder b = SnapshotSection.newBuilder()
.setSnapshotCounter(sm.getSnapshotCounter())
.setNumSnapshots(sm.getNumSnapshots());
INodeDirectory[] snapshottables = sm.getSnapshottableDirs();
for (INodeDirectory sdir : snapshottables) {
b.addSnapshottableDir(sdir.getId());
}
b.build().writeDelimitedTo(out);
int i = 0;
for(INodeDirectory sdir : snapshottables) {
for (Snapshot s : sdir.getDirectorySnapshottableFeature()
.getSnapshotList()) {
Root sroot = s.getRoot();
SnapshotSection.Snapshot.Builder sb = SnapshotSection.Snapshot
.newBuilder().setSnapshotId(s.getId());
INodeSection.INodeDirectory.Builder db = buildINodeDirectory(sroot,
parent.getSaverContext());
INodeSection.INode r = INodeSection.INode.newBuilder()
.setId(sroot.getId())
.setType(INodeSection.INode.Type.DIRECTORY)
.setName(ByteString.copyFrom(sroot.getLocalNameBytes()))
.setDirectory(db).build();
sb.setRoot(r).build().writeDelimitedTo(out);
i++;
if (i % FSImageFormatProtobuf.Saver.CHECK_CANCEL_INTERVAL == 0) {
context.checkCancelled();
}
}
}
Preconditions.checkState(i == sm.getNumSnapshots());
parent.commitSection(headers, FSImageFormatProtobuf.SectionName.SNAPSHOT);
}
/**
* This can only be called after serializing both INode_Dir and SnapshotDiff
*/
public void serializeINodeReferenceSection(OutputStream out)
throws IOException {
final List<INodeReference> refList = parent.getSaverContext()
.getRefList();
for (INodeReference ref : refList) {
INodeReferenceSection.INodeReference.Builder rb = buildINodeReference(ref);
rb.build().writeDelimitedTo(out);
}
parent.commitSection(headers, SectionName.INODE_REFERENCE);
}
private INodeReferenceSection.INodeReference.Builder buildINodeReference(
INodeReference ref) throws IOException {
INodeReferenceSection.INodeReference.Builder rb =
INodeReferenceSection.INodeReference.newBuilder().
setReferredId(ref.getId());
if (ref instanceof WithName) {
rb.setLastSnapshotId(((WithName) ref).getLastSnapshotId()).setName(
ByteString.copyFrom(ref.getLocalNameBytes()));
} else if (ref instanceof DstReference) {
rb.setDstSnapshotId(ref.getDstSnapshotId());
}
return rb;
}
/**
* save all the snapshot diff to fsimage
*/
public void serializeSnapshotDiffSection(OutputStream out)
throws IOException {
INodeMap inodesMap = fsn.getFSDirectory().getINodeMap();
final List<INodeReference> refList = parent.getSaverContext()
.getRefList();
int i = 0;
Iterator<INodeWithAdditionalFields> iter = inodesMap.getMapIterator();
while (iter.hasNext()) {
INodeWithAdditionalFields inode = iter.next();
if (inode.isFile()) {
serializeFileDiffList(inode.asFile(), out);
} else if (inode.isDirectory()) {
serializeDirDiffList(inode.asDirectory(), refList, out);
}
++i;
if (i % FSImageFormatProtobuf.Saver.CHECK_CANCEL_INTERVAL == 0) {
context.checkCancelled();
}
}
parent.commitSection(headers,
FSImageFormatProtobuf.SectionName.SNAPSHOT_DIFF);
}
private void serializeFileDiffList(INodeFile file, OutputStream out)
throws IOException {
FileWithSnapshotFeature sf = file.getFileWithSnapshotFeature();
if (sf != null) {
List<FileDiff> diffList = sf.getDiffs().asList();
SnapshotDiffSection.DiffEntry entry = SnapshotDiffSection.DiffEntry
.newBuilder().setInodeId(file.getId()).setType(Type.FILEDIFF)
.setNumOfDiff(diffList.size()).build();
entry.writeDelimitedTo(out);
for (int i = diffList.size() - 1; i >= 0; i--) {
FileDiff diff = diffList.get(i);
SnapshotDiffSection.FileDiff.Builder fb = SnapshotDiffSection.FileDiff
.newBuilder().setSnapshotId(diff.getSnapshotId())
.setFileSize(diff.getFileSize());
if(diff.getBlocks() != null) {
for(Block block : diff.getBlocks()) {
fb.addBlocks(PBHelper.convert(block));
}
}
INodeFileAttributes copy = diff.snapshotINode;
if (copy != null) {
fb.setName(ByteString.copyFrom(copy.getLocalNameBytes()))
.setSnapshotCopy(buildINodeFile(copy, parent.getSaverContext()));
}
fb.build().writeDelimitedTo(out);
}
}
}
private void saveCreatedList(List<INode> created, OutputStream out)
throws IOException {
// local names of the created list member
for (INode c : created) {
SnapshotDiffSection.CreatedListEntry.newBuilder()
.setName(ByteString.copyFrom(c.getLocalNameBytes())).build()
.writeDelimitedTo(out);
}
}
private void serializeDirDiffList(INodeDirectory dir,
final List<INodeReference> refList, OutputStream out)
throws IOException {
DirectoryWithSnapshotFeature sf = dir.getDirectoryWithSnapshotFeature();
if (sf != null) {
List<DirectoryDiff> diffList = sf.getDiffs().asList();
SnapshotDiffSection.DiffEntry entry = SnapshotDiffSection.DiffEntry
.newBuilder().setInodeId(dir.getId()).setType(Type.DIRECTORYDIFF)
.setNumOfDiff(diffList.size()).build();
entry.writeDelimitedTo(out);
for (int i = diffList.size() - 1; i >= 0; i--) { // reverse order!
DirectoryDiff diff = diffList.get(i);
SnapshotDiffSection.DirectoryDiff.Builder db = SnapshotDiffSection.
DirectoryDiff.newBuilder().setSnapshotId(diff.getSnapshotId())
.setChildrenSize(diff.getChildrenSize())
.setIsSnapshotRoot(diff.isSnapshotRoot());
INodeDirectoryAttributes copy = diff.snapshotINode;
if (!diff.isSnapshotRoot() && copy != null) {
db.setName(ByteString.copyFrom(copy.getLocalNameBytes()))
.setSnapshotCopy(
buildINodeDirectory(copy, parent.getSaverContext()));
}
// process created list and deleted list
List<INode> created = diff.getChildrenDiff()
.getList(ListType.CREATED);
db.setCreatedListSize(created.size());
List<INode> deleted = diff.getChildrenDiff().getList(ListType.DELETED);
for (INode d : deleted) {
if (d.isReference()) {
refList.add(d.asReference());
db.addDeletedINodeRef(refList.size() - 1);
} else {
db.addDeletedINode(d.getId());
}
}
db.build().writeDelimitedTo(out);
saveCreatedList(created, out);
}
}
}
}
private FSImageFormatPBSnapshot(){}
}
| gpl-3.0 |
apartensky/mev | web/src/main/java/edu/dfci/cccb/mev/web/domain/social/Folder.java | 1266 | /**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.dfci.cccb.mev.web.domain.social;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author levk
*
*/
@ToString
@EqualsAndHashCode (callSuper = true)
@RequiredArgsConstructor
@JsonInclude (Include.NON_NULL)
public class Folder extends Entry {
private @Getter final @JsonProperty String name;
private @Getter final @JsonProperty Entry[] entries;
}
| gpl-3.0 |
taimur97/NotePad | app/src/main/java/com/nononsenseapps/notepad/sync/SyncService.java | 1440 | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.nononsenseapps.notepad.sync;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
* Service to handle Account sync. This is invoked with an intent with action
* ACTION_AUTHENTICATOR_INTENT. It instantiates the syncadapter and returns its
* IBinder.
*/
public class SyncService extends Service {
private static final Object sSyncAdapterLock = new Object();
private static SyncAdapter sSyncAdapter = null;
@Override
public void onCreate() {
synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) {
sSyncAdapter = new SyncAdapter(getApplicationContext(), true);
}
}
}
@Override
public IBinder onBind(Intent intent) {
return sSyncAdapter.getSyncAdapterBinder();
}
}
| gpl-3.0 |
Nukkit/Nukkit | src/main/java/cn/nukkit/network/protocol/SetEntityLinkPacket.java | 797 | package cn.nukkit.network.protocol;
/**
* Created on 15-10-22.
*/
public class SetEntityLinkPacket extends DataPacket {
public static final byte NETWORK_ID = ProtocolInfo.SET_ENTITY_LINK_PACKET;
public static final byte TYPE_REMOVE = 0;
public static final byte TYPE_RIDE = 1;
public static final byte TYPE_PASSENGER = 2;
public long rider;
public long riding;
public byte type;
public byte unknownByte;
@Override
public void decode() {
}
@Override
public void encode() {
this.reset();
this.putEntityUniqueId(this.rider);
this.putEntityUniqueId(this.riding);
this.putByte(this.type);
this.putByte(this.unknownByte);
}
@Override
public byte pid() {
return NETWORK_ID;
}
}
| gpl-3.0 |
jeoffz/jpexs-decompiler | libsrc/ffdec_lib/src/com/jpexs/decompiler/graph/GraphPath.java | 4453 | /*
* Copyright (C) 2010-2015 JPEXS, All rights reserved.
*
* 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 3.0 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.
*/
package com.jpexs.decompiler.graph;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
*
* @author JPEXS
*/
public class GraphPath implements Serializable {
private final List<Integer> keys = new ArrayList<>();
private final List<Integer> vals = new ArrayList<>();
public final String rootName;
public GraphPath(String rootName, List<Integer> keys, List<Integer> vals) {
this.rootName = rootName;
this.keys.addAll(keys);
this.vals.addAll(vals);
}
public GraphPath(List<Integer> keys, List<Integer> vals) {
rootName = "";
this.keys.addAll(keys);
this.vals.addAll(vals);
}
public GraphPath() {
rootName = "";
}
public boolean startsWith(GraphPath p) {
if (p.length() > length()) {
return false;
}
List<Integer> otherKeys = new ArrayList<>(p.keys);
List<Integer> otherVals = new ArrayList<>(p.vals);
for (int i = 0; i < p.length(); i++) {
if (!Objects.equals(keys.get(i), otherKeys.get(i))) {
return false;
}
if (!Objects.equals(vals.get(i), otherVals.get(i))) {
return false;
}
}
return true;
}
public GraphPath parent(int len) {
GraphPath par = new GraphPath(rootName);
for (int i = 0; i < len; i++) {
par.keys.add(keys.get(i));
par.vals.add(vals.get(i));
}
return par;
}
public GraphPath sub(int part, int codePos) {
GraphPath next = new GraphPath(rootName, this.keys, this.vals);
next.keys.add(codePos);
next.vals.add(part);
return next;
}
public GraphPath(String rootName) {
this.rootName = rootName;
}
public int length() {
return vals.size();
}
public int get(int index) {
return vals.get(index);
}
public int getKey(int index) {
return keys.get(index);
}
@Override
public int hashCode() {
int hash = 5;
hash = 23 * hash + arrHashCode(keys);
hash = 23 * hash + arrHashCode(vals);
hash = 23 * hash + Objects.hashCode(rootName);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final GraphPath other = (GraphPath) obj;
if ((rootName == null) != (other.rootName == null)) {
return false;
}
if (!Objects.equals(rootName, other.rootName)) {
return false;
}
if (!arrMatch(keys, other.keys)) {
return false;
}
if (!arrMatch(vals, other.vals)) {
return false;
}
return true;
}
private static int arrHashCode(List<Integer> arr) {
if (arr == null || arr.isEmpty()) {
return 0;
}
int hash = 5;
for (Integer i : arr) {
hash = 23 * hash + Objects.hashCode(i);
}
return hash;
}
private static boolean arrMatch(List<Integer> arr, List<Integer> arr2) {
if (arr.size() != arr2.size()) {
return false;
}
for (int i = 0; i < arr.size(); i++) {
if (!Objects.equals(arr.get(i), arr2.get(i))) {
return false;
}
}
return true;
}
@Override
public String toString() {
String ret = rootName;
for (int i = 0; i < keys.size(); i++) {
ret += "/" + keys.get(i) + ":" + vals.get(i);
}
return ret;
}
}
| gpl-3.0 |
coyotesqrl/lux | src/test/java/lux/solr/SchemaTest.java | 5812 | package lux.solr;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.solr.common.SolrInputDocument;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/** Tests for configurable analysis chain */
public class SchemaTest extends BaseSolrTest {
@BeforeClass
public static void setup() throws Exception {
// inhibit the startup of a default core by our superclass
}
@AfterClass
public static void tearDown() throws Exception {
// inhibit the class-level tearDown by our superclass; do it after each test:
}
@After
public void myTearDown () throws Exception {
BaseSolrTest.tearDown();
}
@Test
public void testConfigureXmlAnalyzer () throws Exception {
// schema alters the text analysis used for lux_text, lux_elt_text and lux_att_text as well
BaseSolrTest.setup("solr", "core2");
Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument> ();
addSolrDoc ("test1", "<doc><title id='1'>This is a test</title><test>balloons</test>comma,separated</doc>", docs,
"uri", "xml");
solr.add (docs);
solr.commit();
// lux_text has case-folding, whitespace tokenization, and stemming:
assertSolrQueryCount (1, "balloon");
assertQueryCount (1, 1, "document", "doc", "lux:search('balloon')");
assertSolrQueryCount (1, "balloons");
assertQueryCount (1, 1, "document", "doc", "lux:search('balloons')");
// check that query is analyzed as well
assertSolrQueryCount (1, "tests");
assertQueryCount (1, 1, "document", "doc", "lux:search('tests')");
assertSolrQueryCount (0, "comma");
assertQueryCount (0, 0, "document", "", "lux:search('comma')");
assertSolrQueryCount (1, "comma,separated");
assertQueryCount (1, 1, "document", "doc", "lux:search('comma,separated')");
assertSolrQueryCount (1, "this");
assertQueryCount (1, 1, "document", "doc", "lux:search('this')");
assertSolrQueryCount (1, "This");
assertQueryCount (1, 1, "document", "doc", "lux:search('This')");
// schema includes a copyField from lux_text -> lux_text_unstemmed, which has no stemming
assertSolrQueryCount (1, "lux_text_unstemmed:balloons");
assertQueryCount (1, 1, "document", "doc", "lux:search('lux_text_unstemmed:balloons')");
assertSolrQueryCount (0, "lux_text_unstemmed:balloon");
assertQueryCount (0, 0, "document", "", "lux:search('lux_text_unstemmed:balloon')");
// schema includes a copyField from lux_text -> lux_text_case, which has is case-sensitive
assertSolrQueryCount (0, "lux_text_case:this");
assertQueryCount (0, 0, "document", "", "lux:search('lux_text_case:this')");
assertSolrQueryCount (1, "lux_text_case:This");
assertQueryCount (1, 1, "document", "doc", "lux:search('lux_text_case:This')");
// test that stemming and case-folding have been applied to the element text index as well
assertSolrQueryCount (1, "lux_elt_text:test\\:balloon");
assertQueryCount (1, 1, "document", "doc", "lux:search('<test:balloon')");
// This doesn't work because stemming gets applied to the 'test:balloons'
// but this isn't an issue if we just say that the supported thing is lux:search('<test:balloons')
//assertQueryCount (1, "lux_elt_text:doc\\:balloons");
assertQueryCount (1, 1, "document", "doc", "lux:search('<test:balloons')");
//assertQueryCount (1, "lux_elt_text:doc\\:tests");
assertQueryCount (1, 1, "document", "doc", "lux:search('<title:tests')");
assertSolrQueryCount (0, "lux_elt_text:doc\\:comma");
assertQueryCount (0, 0, "document", "", "lux:search('<doc:comma')");
assertSolrQueryCount (1, "lux_elt_text:doc\\:comma,separated");
assertQueryCount (1, 1, "document", "doc", "lux:search('<doc:comma,separated')");
assertSolrQueryCount (1, "lux_elt_text:title\\:this");
assertQueryCount (1, 1, "document", "doc", "lux:search('<title:this')");
assertSolrQueryCount (1, "lux_elt_text:title\\:This");
assertQueryCount (1, 1, "document", "doc", "lux:search('<title:This')");
}
@Test
public void testDefaultXmlAnalyzer () throws Exception {
// the default analyzer is based on StandardAnalyzer
BaseSolrTest.setup("solr", "collection1");
Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument> ();
addSolrDoc ("test1", "<doc><title id='1'>This is a test</title><test>balloons</test>comma,separated</doc>", docs);
solr.add (docs);
solr.commit();
// lux_text uses the (Lux) default analyzer which has case-folding, standard tokenization, and no stemming:
assertSolrQueryCount (0, "balloon");
assertQueryCount (0, 0, "", "", "lux:search('balloon')");
assertSolrQueryCount (1, "lux_text:balloons");
assertQueryCount (1, 1, "document", "doc", "lux:search('balloons')");
assertSolrQueryCount (1, "lux_text:comma,separated");
assertQueryCount (1, 1, "document", "doc", "lux:search('comma,separated')");
assertSolrQueryCount (1, "lux_text:comma");
assertQueryCount (1, 1, "document", "doc", "lux:search('comma')");
assertSolrQueryCount (1, "lux_text:this");
assertQueryCount (1, 1, "document", "doc", "lux:search('this')");
assertSolrQueryCount (1, "lux_text:This");
}
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
| mpl-2.0 |
tdefilip/opennms | opennms-tools/sms-reflector/sms-monitor/src/main/java/org/opennms/sms/monitor/internal/config/SmsSequenceResponse.java | 2888 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2009-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.sms.monitor.internal.config;
import javax.xml.bind.annotation.XmlRootElement;
import org.opennms.sms.monitor.MobileSequenceSession;
import org.opennms.sms.reflector.smsservice.MobileMsgRequest;
import org.opennms.sms.reflector.smsservice.MobileMsgResponse;
import org.opennms.sms.reflector.smsservice.SmsResponse;
/**
* <p>SmsSequenceResponse class.</p>
*
* @author ranger
* @version $Id: $
*/
@XmlRootElement(name="sms-response")
public class SmsSequenceResponse extends MobileSequenceResponse {
/**
* <p>Constructor for SmsSequenceResponse.</p>
*/
public SmsSequenceResponse() {
super();
}
/**
* <p>Constructor for SmsSequenceResponse.</p>
*
* @param label a {@link java.lang.String} object.
*/
public SmsSequenceResponse(String label) {
super(label);
}
/**
* <p>Constructor for SmsSequenceResponse.</p>
*
* @param gatewayId a {@link java.lang.String} object.
* @param label a {@link java.lang.String} object.
*/
public SmsSequenceResponse(String gatewayId, String label) {
super(gatewayId, label);
}
/** {@inheritDoc} */
@Override
protected boolean matchesResponseType(MobileMsgRequest request, MobileMsgResponse response) {
return response instanceof SmsResponse;
}
/** {@inheritDoc} */
@Override
public void processResponse(MobileSequenceSession session, MobileMsgRequest request, MobileMsgResponse response) {
if (response instanceof SmsResponse) {
SmsResponse smsResponse = (SmsResponse)response;
session.setVariable(getEffectiveLabel(session)+".smsOriginator", smsResponse.getOriginator());
}
}
}
| agpl-3.0 |
olivermay/geomajas | plugin/geomajas-plugin-editing/editing/src/main/java/org/geomajas/plugin/editing/client/merge/event/GeometryMergeRemovedHandler.java | 1258 | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2013 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.plugin.editing.client.merge.event;
import org.geomajas.annotation.Api;
import org.geomajas.annotation.UserImplemented;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
/**
* Handler for catching events for geometries being removed from the merging list.
*
* @author Pieter De Graef
* @since 1.0.0
*/
@Api(allMethods = true)
@UserImplemented
public interface GeometryMergeRemovedHandler extends EventHandler {
/** Type of this handler. */
GwtEvent.Type<GeometryMergeRemovedHandler> TYPE = new GwtEvent.Type<GeometryMergeRemovedHandler>();
/**
* Executed when a geometry has been removed from the list for merging.
*
* @param event
* The geometry merging remove event.
*/
void onGeometryMergingRemoved(GeometryMergeRemovedEvent event);
} | agpl-3.0 |
aihua/opennms | opennms-config-model/src/test/java/org/opennms/netmgt/config/tl1d/Tl1dConfigurationTest.java | 3155 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2017-2017 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2017 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.config.tl1d;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collection;
import org.junit.runners.Parameterized.Parameters;
import org.opennms.core.test.xml.XmlTestNoCastor;
public class Tl1dConfigurationTest extends XmlTestNoCastor<Tl1dConfiguration> {
public Tl1dConfigurationTest(Tl1dConfiguration sampleObject, Object sampleXml) {
super(sampleObject, sampleXml, "src/main/resources/xsds/tl1d-configuration.xsd");
}
@Parameters
public static Collection<Object[]> data() throws ParseException {
return Arrays.asList(new Object[][] {
{
getConfig(),
"<tl1d-configuration>\n" +
" <tl1-element host=\"127.0.0.1\" \n" +
" port=\"15001\" \n" +
" password=\"opennms\" \n" +
" reconnect-delay=\"30000\" \n" +
" tl1-client-api=\"org.opennms.netmgt.tl1d.Tl1ClientImpl\"\n" +
" tl1-message-parser=\"org.opennms.netmgt.tl1d.Tl1AutonomousMessageProcessor\" \n" +
" userid=\"opennms\"/>\n" +
"</tl1d-configuration>"
},
{
new Tl1dConfiguration(),
"<tl1d-configuration/>"
}
});
}
private static Tl1dConfiguration getConfig() {
Tl1dConfiguration config = new Tl1dConfiguration();
Tl1Element el = new Tl1Element();
el.setHost("127.0.0.1");
el.setPort(15001);
el.setPassword("opennms");
el.setReconnectDelay(30000L);
el.setTl1ClientApi("org.opennms.netmgt.tl1d.Tl1ClientImpl");
el.setTl1MessageParser("org.opennms.netmgt.tl1d.Tl1AutonomousMessageProcessor");
el.setUserid("opennms");
config.addTl1Element(el);
return config;
}
}
| agpl-3.0 |
roskens/opennms-pre-github | opennms-services/src/main/java/org/opennms/netmgt/poller/monitors/MemcachedMonitor.java | 8438 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2002-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.poller.monitors;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NoRouteToHostException;
import java.net.Socket;
import java.util.LinkedHashMap;
import java.util.Map;
import org.opennms.core.utils.InetAddressUtils;
import org.opennms.core.utils.ParameterMap;
import org.opennms.core.utils.TimeoutTracker;
import org.opennms.netmgt.poller.Distributable;
import org.opennms.netmgt.poller.MonitoredService;
import org.opennms.netmgt.poller.PollStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is designed to be used by the service poller framework to test the
* availability of the Memcached service on remote interfaces. The class implements
* the ServiceMonitor interface that allows it to be used along with other
* plug-ins by the service poller framework.
*
* @author <A HREF="mailto:ranger@opennms.org">Benjamin Reed</A>
*/
@Distributable
final public class MemcachedMonitor extends AbstractServiceMonitor {
public static final Logger LOG = LoggerFactory.getLogger(MemcachedMonitor.class);
/**
* Default FTP port.
*/
private static final int DEFAULT_PORT = 11211;
/**
* Default retries.
*/
private static final int DEFAULT_RETRY = 0;
/**
* Default timeout. Specifies how long (in milliseconds) to block waiting
* for data from the monitored interface.
*/
private static final int DEFAULT_TIMEOUT = 3000; // 3 second timeout on read()
private static final String[] m_keys = new String[] {
"uptime", "rusageuser", "rusagesystem",
"curritems", "totalitems", "bytes", "limitmaxbytes",
"currconnections", "totalconnections", "connectionstructure",
"cmdget", "cmdset", "gethits", "getmisses", "evictions",
"bytesread", "byteswritten", "threads"
};
/**
* {@inheritDoc}
*
* Poll the specified address for Memcached service availability.
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
TimeoutTracker timeoutTracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);
// Extract the address
InetAddress ipv4Addr = svc.getAddress();
String host = InetAddressUtils.str(ipv4Addr);
LOG.debug("polling interface: {} {}", host, timeoutTracker);
PollStatus serviceStatus = PollStatus.unavailable();
for(timeoutTracker.reset(); timeoutTracker.shouldRetry() && !serviceStatus.isAvailable(); timeoutTracker.nextAttempt()) {
Socket socket = null;
try {
timeoutTracker.startAttempt();
socket = new Socket();
socket.connect(new InetSocketAddress(ipv4Addr, port), timeoutTracker.getConnectionTimeout());
socket.setSoTimeout(timeoutTracker.getSoTimeout());
LOG.debug("connected to host: {} on port: {}", host, port);
// We're connected, so upgrade status to unresponsive
serviceStatus = PollStatus.unresponsive();
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
osw.write("stats\n");
osw.flush();
// Allocate a line reader
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Map<String, Number> statProps = new LinkedHashMap<String,Number>();
for (String key : m_keys) {
statProps.put(key, null);
}
String line = null;
do {
line = reader.readLine();
if (line == null) break;
String[] statEntry = line.trim().split("\\s", 3);
if (statEntry[0].equals("STAT")) {
try {
Number value;
if (statEntry[2].contains(".")) {
value = Double.parseDouble(statEntry[2]);
} else {
value = Long.parseLong(statEntry[2]);
}
String key = statEntry[1].toLowerCase();
key = key.replaceAll("_", "");
if (key.length() > 19) {
key = key.substring(0, 19);
}
if (statProps.containsKey(key)) {
statProps.put(key, value);
}
} catch (Throwable e) {
// ignore errors parsing
}
} else if (statEntry[0].equals("END")) {
serviceStatus = PollStatus.available();
osw.write("quit\n");
osw.flush();
break;
}
} while (line != null);
serviceStatus.setProperties(statProps);
serviceStatus.setResponseTime(timeoutTracker.elapsedTimeInMillis());
} catch (ConnectException e) {
// Connection refused!! Continue to retry.
String reason = "Connection refused by host "+host;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (NoRouteToHostException e) {
// No route to host!! Try retries anyway in case strict timeouts are enabled
String reason = "Unable to test host " + host + ", no route available";
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (InterruptedIOException e) {
String reason = "did not connect to host " + host +" within timeout: " + timeoutTracker;
LOG.debug(reason);
serviceStatus = PollStatus.unavailable(reason);
} catch (IOException e) {
String reason = "Error communicating with host " + host;
LOG.debug(reason, e);
serviceStatus = PollStatus.unavailable(reason);
} catch (Throwable t) {
String reason = "Undeclared throwable exception caught contacting host " + host;
LOG.debug(reason, t);
serviceStatus = PollStatus.unavailable(reason);
} finally {
try {
if (socket != null) {
socket.close();
socket = null;
}
} catch (IOException e) {
}
}
}
//
// return the status of the service
//
return serviceStatus;
}
}
| agpl-3.0 |
blue-systems-group/project.maybe.polyglot | src/polyglot/ext/jl5/ast/ParamTypeNode.java | 1505 | /*******************************************************************************
* This file is part of the Polyglot extensible compiler framework.
*
* Copyright (c) 2000-2012 Polyglot project group, Cornell University
* Copyright (c) 2006-2012 IBM Corporation
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License v1.0 which accompanies this
* distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This program and the accompanying materials are made available under
* the terms of the Lesser GNU Public License v2.0 which accompanies this
* distribution.
*
* The development of the Polyglot project has been supported by a
* number of funding sources, including DARPA Contract F30602-99-1-0533,
* monitored by USAF Rome Laboratory, ONR Grants N00014-01-1-0968 and
* N00014-09-1-0652, NSF Grants CNS-0208642, CNS-0430161, CCF-0133302,
* and CCF-1054172, AFRL Contract FA8650-10-C-7022, an Alfred P. Sloan
* Research Fellowship, and an Intel Research Ph.D. Fellowship.
*
* See README for contributors.
******************************************************************************/
package polyglot.ext.jl5.ast;
import java.util.List;
import polyglot.ast.Id;
import polyglot.ast.TypeNode;
public interface ParamTypeNode extends TypeNode {
Id id();
ParamTypeNode id(Id id);
List<TypeNode> bounds();
ParamTypeNode bounds(List<TypeNode> bounds);
}
| lgpl-2.1 |
0xbb/jitsi | src/net/java/sip/communicator/plugin/sip2sipaccregwizz/Sip2SipAccountRegistrationWizard.java | 7503 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.plugin.sip2sipaccregwizz;
import java.util.*;
import net.java.sip.communicator.plugin.sipaccregwizz.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.protocol.sip.*;
/**
* The <tt>Sip2SipAccountRegistrationWizard</tt> is an implementation of the
* <tt>AccountRegistrationWizard</tt> for the SIP protocol. It should allow
* the user to create and configure a new IP Tel SIP account.
*
* @author Yana Stamcheva
*/
public class Sip2SipAccountRegistrationWizard
extends SIPAccountRegistrationWizard
{
/**
* A constant pointing to the IP Tel protocol logo image.
*/
private static final String PROTOCOL_ICON
= "service.protocol.sip2sip.SIP2SIP_16x16";
/**
* A constant pointing to the IP Tel protocol wizard page image.
*/
private static final String PAGE_IMAGE
= "service.protocol.sip2sip.SIP2SIP_64x64";
/**
* The protocol name.
*/
public static final String PROTOCOL = "sip2sip.info";
/**
* The create account form.
*/
CreateSip2SipAccountForm createAccountForm = new CreateSip2SipAccountForm();
/**
* Creates an instance of <tt>IptelAccountRegistrationWizard</tt>.
* @param wizardContainer the wizard container
*/
public Sip2SipAccountRegistrationWizard(WizardContainer wizardContainer)
{
super(wizardContainer);
}
/**
* Returns the set of pages contained in this wizard.
* @return Iterator
*/
@Override
public Iterator<WizardPage> getPages()
{
SIPAccountRegistration reg = new SIPAccountRegistration();
setPredefinedProperties(reg);
return getPages(reg);
}
/**
* Returns a simple account registration form that would be the first form
* shown to the user. Only if the user needs more settings she'll choose
* to open the advanced wizard, consisted by all pages.
*
* @param isCreateAccount indicates if the simple form should be opened as
* a create account form or as a login form
* @return a simple account registration form
*/
@Override
public Object getSimpleForm(boolean isCreateAccount)
{
SIPAccountRegistration reg = new SIPAccountRegistration();
setPredefinedProperties(reg);
return getSimpleForm(reg, isCreateAccount);
}
/**
* Sets all predefined properties specific for this account wizard.
*
* @param reg the registration object
*/
private void setPredefinedProperties(SIPAccountRegistration reg)
{
// set properties common for sip2sip
reg.setKeepAliveMethod("NONE");
reg.setDefaultDomain("sip2sip.info");
reg.setXCapEnable(true);
reg.setClistOptionServerUri(
"https://xcap.sipthor.net/xcap-root@sip2sip.info");
reg.setClistOptionUseSipCredentials(true);
}
/**
* Implements the <code>AccountRegistrationWizard.getIcon</code> method.
* Returns the icon to be used for this wizard.
* @return byte[]
*/
@Override
public byte[] getIcon()
{
return Sip2SipAccRegWizzActivator.getResources()
.getImageInBytes(PROTOCOL_ICON);
}
/**
* Implements the <code>AccountRegistrationWizard.getPageImage</code> method.
* Returns the image used to decorate the wizard page
*
* @return byte[] the image used to decorate the wizard page
*/
@Override
public byte[] getPageImage()
{
return Sip2SipAccRegWizzActivator.getResources()
.getImageInBytes(PAGE_IMAGE);
}
/**
* Implements the <code>AccountRegistrationWizard.getProtocolName</code>
* method. Returns the protocol name for this wizard.
* @return String
*/
@Override
public String getProtocolName()
{
return Resources.getString(
"plugin.sip2sipaccregwizz.PROTOCOL_NAME");
}
/**
* Implements the <code>AccountRegistrationWizard.getProtocolDescription
* </code> method. Returns the description of the protocol for this wizard.
* @return String
*/
@Override
public String getProtocolDescription()
{
return Resources.getString(
"plugin.sip2sipaccregwizz.PROTOCOL_DESCRIPTION");
}
/**
* Returns an example string, which should indicate to the user how the
* user name should look like.
* @return an example string, which should indicate to the user how the
* user name should look like.
*/
@Override
public String getUserNameExample()
{
return "Ex: myusername or myusername@sip2sip.info";
}
/**
* Returns the protocol name as listed in "ProtocolNames" or just the name
* of the service.
* @return the protocol name
*/
@Override
public String getProtocol()
{
return PROTOCOL;
}
/**
* Returns the protocol icon path.
* @return the protocol icon path
*/
@Override
public String getProtocolIconPath()
{
return "resources/images/protocol/sip2sip";
}
/**
* Returns the account icon path.
* @return the account icon path
*/
@Override
public String getAccountIconPath()
{
return "resources/images/protocol/sip2sip/sip32x32.png";
}
/**
* Opens the browser on the page sign up
*/
@Override
public void webSignup()
{
Sip2SipAccRegWizzActivator.getBrowserLauncher()
.openURL("http://wiki.sip2sip.info");
}
/**
* Returns the name of the web sign up link.
* @return the name of the web sign up link
*/
@Override
public String getWebSignupLinkName()
{
return Resources.getString("plugin.sip2sipaccregwizz.NEW_ACCOUNT_TITLE");
}
/**
* Returns an instance of <tt>CreateAccountService</tt> through which the
* user could create an account. This method is meant to be implemented by
* specific protocol provider wizards.
* @return an instance of <tt>CreateAccountService</tt>
*/
@Override
protected SIPAccountCreationFormService getCreateAccountService()
{
return createAccountForm;
}
/**
* Returns the display label used for the sip id field.
* @return the sip id display label string.
*/
@Override
protected String getUsernameLabel()
{
return Resources.getString("plugin.sip2sipaccregwizz.USERNAME");
}
/**
* Return the string for add existing account button.
* @return the string for add existing account button.
*/
@Override
protected String getExistingAccountLabel()
{
return Resources.getString("plugin.sip2sipaccregwizz.EXISTING_ACCOUNT");
}
/**
* Return the string for create new account button.
* @return the string for create new account button.
*/
@Override
protected String getCreateAccountLabel()
{
return Resources.getString("plugin.sip2sipaccregwizz.CREATE_ACCOUNT");
}
}
| lgpl-2.1 |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/activity/ViewPhotoActivity.java | 1673 | package com.rapidftr.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import com.rapidftr.R;
import com.rapidftr.utils.PhotoCaptureHelper;
public class ViewPhotoActivity extends RapidFtrActivity {
protected PhotoCaptureHelper photoCaptureHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
photoCaptureHelper = new PhotoCaptureHelper(getContext());
this.initialize();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (getIntent().getBooleanExtra("enabled", false)) {
getMenuInflater().inflate(R.menu.image_menu, menu);
return true;
}
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.set_as_primary:
Intent intent = new Intent();
intent.putExtra("file_name", getIntent().getStringExtra("file_name"));
setResult(RESULT_OK, intent);
finish();
}
return true;
}
protected ImageView getImageView() {
return (ImageView) findViewById(R.id.photo);
}
public void initialize() {
setContentView(R.layout.activity_view_photo);
String fileName = getIntent().getStringExtra("file_name");
try {
getImageView().setImageBitmap(photoCaptureHelper.loadPhoto(fileName));
} catch (Exception e) {
makeToast(R.string.photo_view_error);
}
}
}
| lgpl-3.0 |
Decentrify/NatTraversal_Old | network/netty/src/main/java/se/sics/gvod/common/msgs/RelayMsgNettyFactory.java | 3314 | package se.sics.gvod.common.msgs;
import io.netty.buffer.ByteBuf;
import java.util.Set;
import se.sics.gvod.address.Address;
import se.sics.gvod.net.VodAddress;
import se.sics.gvod.net.msgs.RewriteableMsg;
import se.sics.gvod.net.util.UserTypesDecoderFactory;
public abstract class RelayMsgNettyFactory {
static abstract class Base extends RewriteableMsgNettyFactory {
protected VodAddress gvodDest;
protected VodAddress gvodSrc;
protected VodAddress nextDest;
protected int clientId;
protected int remoteId;
protected Base() {
super();
}
@Override
protected void decodeHeader(ByteBuf buffer, boolean timeout)
throws MessageDecodingException {
super.decodeHeader(buffer, timeout);
int srcOverlayId = buffer.readInt();
int srcNatPolicy = UserTypesDecoderFactory.readUnsignedIntAsOneByte(buffer);
Set<Address> parents = UserTypesDecoderFactory.readListAddresses(buffer);
int destOverlayId = buffer.readInt();
int destNatPolicy = UserTypesDecoderFactory.readUnsignedIntAsOneByte(buffer);
gvodSrc = new VodAddress(src, srcOverlayId, (short) srcNatPolicy, parents);
gvodDest = new VodAddress(dest, destOverlayId, (short) destNatPolicy, null);
nextDest = UserTypesDecoderFactory.readVodAddress(buffer);
clientId = buffer.readInt();
remoteId = buffer.readInt();
}
}
public abstract static class Request extends Base {
protected RewriteableMsg decode(ByteBuf buffer) throws MessageDecodingException {
return super.decode(buffer, true);
}
@Override
protected RewriteableMsg decode(ByteBuf buffer, boolean timeout) throws MessageDecodingException {
throw new UnsupportedOperationException("Call decode() without timeout parameter");
}
}
public abstract static class Response extends Base {
protected RelayMsgNetty.Status status;
protected Response() {
}
protected RewriteableMsg decode(ByteBuf buffer) throws MessageDecodingException {
return super.decode(buffer, true);
}
@Override
protected RewriteableMsg decode(ByteBuf buffer, boolean timeout) throws MessageDecodingException {
throw new UnsupportedOperationException("Call decode() without timeout parameter");
}
@Override
protected void decodeHeader(ByteBuf buffer, boolean timeout)
throws MessageDecodingException {
super.decodeHeader(buffer, true);
int statusVal = UserTypesDecoderFactory.readUnsignedIntAsOneByte(buffer);
status = RelayMsgNetty.Status.create(statusVal);
}
}
public abstract static class Oneway extends Base {
protected RewriteableMsg decode(ByteBuf buffer) throws MessageDecodingException {
return super.decode(buffer, false);
}
@Override
protected RewriteableMsg decode(ByteBuf buffer, boolean timeout) throws MessageDecodingException {
throw new UnsupportedOperationException("Call decode() without timeout parameter");
}
}
};
| lgpl-3.0 |
FenixEdu/fenixedu-academic | src/main/java/org/fenixedu/academic/domain/accessControl/StudentsConcludedInExecutionYearGroup.java | 5739 | /**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic 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 3 of the License, or
* (at your option) any later version.
*
* FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.domain.accessControl;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
import org.fenixedu.academic.domain.Degree;
import org.fenixedu.academic.domain.ExecutionYear;
import org.fenixedu.academic.domain.StudentCurricularPlan;
import org.fenixedu.academic.domain.student.Registration;
import org.fenixedu.bennu.core.annotation.GroupArgument;
import org.fenixedu.bennu.core.annotation.GroupOperator;
import org.fenixedu.bennu.core.domain.User;
import org.fenixedu.bennu.core.domain.groups.PersistentGroup;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.YearMonthDay;
import com.google.common.base.Objects;
@GroupOperator("studentsConcluded")
public class StudentsConcludedInExecutionYearGroup extends FenixGroup {
private static final long serialVersionUID = 5303530923037645419L;
@GroupArgument
private Degree degree;
@GroupArgument
private ExecutionYear conclusionYear;
private StudentsConcludedInExecutionYearGroup() {
super();
}
private StudentsConcludedInExecutionYearGroup(Degree degree, ExecutionYear conclusionYear) {
this();
this.degree = degree;
this.conclusionYear = conclusionYear;
}
public static StudentsConcludedInExecutionYearGroup get(Degree degree, ExecutionYear conclusionYear) {
return new StudentsConcludedInExecutionYearGroup(degree, conclusionYear);
}
@Override
public String[] getPresentationNameKeyArgs() {
return new String[] { degree.getPresentationName(), conclusionYear.getName() };
}
@Override
public Stream<User> getMembers() {
Set<User> users = new HashSet<User>();
for (Registration registration : degree.getRegistrationsSet()) {
if (registration.hasConcluded()) {
LocalDate conclusionDate = getConclusionDate(degree, registration);
if (conclusionDate != null
&& (conclusionDate.getYear() == conclusionYear.getEndCivilYear() || conclusionDate.getYear() == conclusionYear
.getBeginCivilYear())) {
User user = registration.getPerson().getUser();
if (user != null) {
users.add(user);
}
}
}
}
return users.stream();
}
@Override
public Stream<User> getMembers(DateTime when) {
return getMembers();
}
@Override
public boolean isMember(User user) {
if (user == null || user.getPerson().getStudent() == null) {
return false;
}
for (final Registration registration : user.getPerson().getStudent().getRegistrationsSet()) {
if (registration.isConcluded() && registration.getDegree().equals(degree)) {
LocalDate conclusionDate = getConclusionDate(registration.getDegree(), registration);
if (conclusionDate != null
&& (conclusionDate.getYear() == conclusionYear.getEndCivilYear() || conclusionDate.getYear() == conclusionYear
.getBeginCivilYear())) {
return true;
}
return false;
}
}
return false;
}
@Override
public boolean isMember(User user, DateTime when) {
return isMember(user);
}
private LocalDate getConclusionDate(Degree degree, Registration registration) {
for (StudentCurricularPlan scp : registration.getStudentCurricularPlansByDegree(degree)) {
if (registration.isBolonha()) {
if (scp.getLastConcludedCycleCurriculumGroup() != null) {
YearMonthDay conclusionDate =
registration.getConclusionDate(scp.getLastConcludedCycleCurriculumGroup().getCycleType());
if (conclusionDate != null) {
return conclusionDate.toLocalDate();
}
}
return null;
} else {
return registration.getConclusionDate() != null ? registration.getConclusionDate().toLocalDate() : null;
}
}
return null;
}
@Override
public PersistentGroup toPersistentGroup() {
return PersistentStudentsConcludedInExecutionYearGroup.getInstance(degree, conclusionYear);
}
@Override
public boolean equals(Object object) {
if (object instanceof StudentsConcludedInExecutionYearGroup) {
StudentsConcludedInExecutionYearGroup other = (StudentsConcludedInExecutionYearGroup) object;
return Objects.equal(degree, other.degree) && Objects.equal(conclusionYear, other.conclusionYear);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(degree, conclusionYear);
}
}
| lgpl-3.0 |
huberflores/NQueensCodeOffloading | NQueens_Server/src/cs/ut/ee/characterization/Characterization.java | 753 | package cs.ut.ee.characterization;
import java.util.List;
import com.google.gson.annotations.Expose;
/**
* @author Huber Flores
*/
public abstract class Characterization {
@Expose
private String mobileApplication;
@Expose
private String deviceID;
@Expose
private String description;
@Expose
private List<String> candidateComponents;
@Expose
private List<Set> variables;
@Expose
private List<Rule> rules;
//@Expose
//private List<ExecutionPlan> plans;
public List<String> getMobileComponents() {
return candidateComponents;
}
public String getMobileApplication(){
return mobileApplication;
}
public List<Set> getVariables(){
return variables;
}
public List<Rule> getRules(){
return rules;
}
}
| lgpl-3.0 |
Alfresco/community-edition | projects/file-transfer-receiver/source/java/org/alfresco/repo/web/scripts/transfer/FileTransferWebScript.java | 5236 | /*
* #%L
* Alfresco File Transfer Receiver
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco 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 3 of the License, or
* (at your option) any later version.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.web.scripts.transfer;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
import org.alfresco.service.cmr.transfer.TransferException;
import org.alfresco.util.json.ExceptionJsonSerializer;
import org.alfresco.util.json.JsonSerializer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.AbstractWebScript;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.WebScriptResponse;
/**
* @author brian
*
*/
public class FileTransferWebScript extends AbstractWebScript
{
private static final Log log = LogFactory.getLog(TransferWebScript.class);
private boolean enabled = true;
private Map<String, CommandProcessor> processors = new TreeMap<String, CommandProcessor>();
private JsonSerializer<Throwable, JSONObject> errorSerializer = new ExceptionJsonSerializer();
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
public void setCommandProcessors(Map<String, CommandProcessor> processors)
{
this.processors = new TreeMap<String,CommandProcessor>(processors);
}
/* (non-Javadoc)
* @see org.alfresco.web.scripts.WebScript#execute(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.WebScriptResponse)
*/
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException
{
if (enabled)
{
//log.debug("Transfer webscript invoked by user: " + AuthenticationUtil.getFullyAuthenticatedUser() +
// " running as " + AuthenticationUtil.getRunAsAuthentication().getName());
processCommand(req.getServiceMatch().getTemplateVars().get("command"), req, res);
}
else
{
res.setStatus(Status.STATUS_NOT_FOUND);
}
}
/**
* @param command String
* @param req WebScriptRequest
* @param res WebScriptResponse
*/
private void processCommand(String command, WebScriptRequest req, WebScriptResponse res)
{
log.debug("Received request to process transfer command: " + command);
if (command == null || (command = command.trim()).length() == 0)
{
log.warn("Empty or null command received by the transfer script. Returning \"Not Found\"");
res.setStatus(Status.STATUS_NOT_FOUND);
}
else
{
CommandProcessor processor = processors.get(command);
if (processor != null)
{
log.debug("Found appropriate command processor: " + processor);
try
{
processor.process(req, res);
log.debug("command processed");
}
catch (TransferException ex)
{
try
{
log.debug("transfer exception caught", ex);
res.setStatus(Status.STATUS_INTERNAL_SERVER_ERROR);
JSONObject errorObject = errorSerializer.serialize(ex);
String error = errorObject.toString();
res.setContentType("application/json");
res.setContentEncoding("UTF-8");
int length = error.getBytes("UTF-8").length;
res.addHeader("Content-Length", "" + length);
res.getWriter().write(error);
}
catch (Exception e)
{
//nothing to do at this point really.
}
}
}
else
{
log.warn("No processor found for requested command: " + command + ". Returning \"Not Found\"");
res.setStatus(Status.STATUS_NOT_FOUND);
}
}
}
}
| lgpl-3.0 |
KidEinstein/giraph | giraph-block-app/src/main/java/org/apache/giraph/block_app/reducers/array/ArrayReduce.java | 7313 | /*
* 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.giraph.block_app.reducers.array;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.reflect.Array;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.giraph.block_app.framework.api.BlockMasterApi;
import org.apache.giraph.block_app.framework.api.CreateReducersApi.CreateReducerFunctionApi;
import org.apache.giraph.block_app.framework.piece.global_comm.BroadcastHandle;
import org.apache.giraph.block_app.framework.piece.global_comm.ReducerHandle;
import org.apache.giraph.block_app.framework.piece.global_comm.array.BroadcastArrayHandle;
import org.apache.giraph.block_app.framework.piece.global_comm.array.ReducerArrayHandle;
import org.apache.giraph.function.primitive.PrimitiveRefs.IntRef;
import org.apache.giraph.master.MasterGlobalCommUsage;
import org.apache.giraph.reducers.ReduceOperation;
import org.apache.giraph.utils.ArrayWritable;
import org.apache.giraph.utils.WritableUtils;
import org.apache.giraph.worker.WorkerBroadcastUsage;
import org.apache.hadoop.io.Writable;
/**
* One reducer representing reduction of array of individual values.
* Elements are represented as object, and so BasicArrayReduce should be
* used instead when elements are primitive types.
*
* @param <S> Single value type, objects passed on workers
* @param <R> Reduced value type
*/
public class ArrayReduce<S, R extends Writable>
implements ReduceOperation<Pair<IntRef, S>, ArrayWritable<R>> {
private int fixedSize;
private ReduceOperation<S, R> elementReduceOp;
private Class<R> elementClass;
public ArrayReduce() {
}
/**
* Create ReduceOperation that reduces arrays by reducing individual
* elements.
*
* @param fixedSize Number of elements
* @param elementReduceOp ReduceOperation for individual elements
*/
public ArrayReduce(int fixedSize, ReduceOperation<S, R> elementReduceOp) {
this.fixedSize = fixedSize;
this.elementReduceOp = elementReduceOp;
init();
}
/**
* Registers one new reducer, that will reduce array of objects,
* by reducing individual elements using {@code elementReduceOp}.
*
* This function will return ReducerArrayHandle to it, by which
* individual elements can be manipulated separately.
*
* @param fixedSize Number of elements
* @param elementReduceOp ReduceOperation for individual elements
* @param createFunction Function for creating a reducer
* @return Created ReducerArrayHandle
*/
public static <S, T extends Writable>
ReducerArrayHandle<S, T> createArrayHandles(
final int fixedSize, ReduceOperation<S, T> elementReduceOp,
CreateReducerFunctionApi createFunction) {
final ReducerHandle<Pair<IntRef, S>, ArrayWritable<T>> reduceHandle =
createFunction.createReducer(
new ArrayReduce<>(fixedSize, elementReduceOp));
final IntRef curIndex = new IntRef(0);
final MutablePair<IntRef, S> reusablePair =
MutablePair.of(new IntRef(0), null);
final ReducerHandle<S, T> elementReduceHandle = new ReducerHandle<S, T>() {
@Override
public T getReducedValue(MasterGlobalCommUsage master) {
ArrayWritable<T> result = reduceHandle.getReducedValue(master);
return result.get()[curIndex.value];
}
@Override
public void reduce(S valueToReduce) {
reusablePair.getLeft().value = curIndex.value;
reusablePair.setRight(valueToReduce);
reduceHandle.reduce(reusablePair);
}
@Override
public BroadcastHandle<T> broadcastValue(BlockMasterApi master) {
throw new UnsupportedOperationException();
}
};
return new ReducerArrayHandle<S, T>() {
@Override
public ReducerHandle<S, T> get(int index) {
curIndex.value = index;
return elementReduceHandle;
}
@Override
public int getStaticSize() {
return fixedSize;
}
@Override
public int getReducedSize(BlockMasterApi master) {
return getStaticSize();
}
@Override
public BroadcastArrayHandle<T> broadcastValue(BlockMasterApi master) {
final BroadcastHandle<ArrayWritable<T>> broadcastHandle =
reduceHandle.broadcastValue(master);
final IntRef curIndex = new IntRef(0);
final BroadcastHandle<T>
elementBroadcastHandle = new BroadcastHandle<T>() {
@Override
public T getBroadcast(WorkerBroadcastUsage worker) {
ArrayWritable<T> result = broadcastHandle.getBroadcast(worker);
return result.get()[curIndex.value];
}
};
return new BroadcastArrayHandle<T>() {
@Override
public BroadcastHandle<T> get(int index) {
curIndex.value = index;
return elementBroadcastHandle;
}
@Override
public int getStaticSize() {
return fixedSize;
}
@Override
public int getBroadcastedSize(WorkerBroadcastUsage worker) {
return getStaticSize();
}
};
}
};
}
private void init() {
elementClass = (Class<R>) elementReduceOp.createInitialValue().getClass();
}
@Override
public ArrayWritable<R> createInitialValue() {
R[] values = (R[]) Array.newInstance(elementClass, fixedSize);
for (int i = 0; i < fixedSize; i++) {
values[i] = elementReduceOp.createInitialValue();
}
return new ArrayWritable<>(elementClass, values);
}
@Override
public ArrayWritable<R> reduce(
ArrayWritable<R> curValue, Pair<IntRef, S> valueToReduce) {
int index = valueToReduce.getLeft().value;
curValue.get()[index] =
elementReduceOp.reduce(curValue.get()[index], valueToReduce.getRight());
return curValue;
}
@Override
public ArrayWritable<R> reduceMerge(
ArrayWritable<R> curValue, ArrayWritable<R> valueToReduce) {
for (int i = 0; i < fixedSize; i++) {
curValue.get()[i] =
elementReduceOp.reduceMerge(
curValue.get()[i], valueToReduce.get()[i]);
}
return curValue;
}
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(fixedSize);
WritableUtils.writeWritableObject(elementReduceOp, out);
}
@Override
public void readFields(DataInput in) throws IOException {
fixedSize = in.readInt();
elementReduceOp = WritableUtils.readWritableObject(in, null);
init();
}
}
| apache-2.0 |
tectronics/splinelibrary | 2.3/src/org/drip/analytics/holset/TWDHoliday.java | 46882 |
package org.drip.analytics.holset;
/*
* -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*/
/*
* GENERATED on Fri Jan 11 19:54:07 EST 2013 ---- DO NOT DELETE
*/
/*!
* Copyright (C) 2013 Lakshmi Krishnamurthy
* Copyright (C) 2012 Lakshmi Krishnamurthy
* Copyright (C) 2011 Lakshmi Krishnamurthy
*
* This file is part of CreditAnalytics, a free-software/open-source library for
* fixed income analysts and developers - http://www.credit-trader.org
*
* CreditAnalytics is a free, full featured, fixed income credit analytics library, developed with a special focus
* towards the needs of the bonds and credit products community.
*
* 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.
*/
public class TWDHoliday implements org.drip.analytics.holset.LocationHoliday {
public TWDHoliday()
{
}
public java.lang.String getHolidayLoc()
{
return "TWD";
}
public org.drip.analytics.holiday.Locale getHolidaySet()
{
org.drip.analytics.holiday.Locale lh = new
org.drip.analytics.holiday.Locale();
lh.addStaticHoliday ("01-JAN-1999", "New Years Day");
lh.addStaticHoliday ("02-JAN-1999", "Bank Holiday");
lh.addStaticHoliday ("04-JAN-1999", "Bank Holiday Observed");
lh.addStaticHoliday ("15-FEB-1999", "Lunar New Years Eve");
lh.addStaticHoliday ("16-FEB-1999", "Lunar New Years Day");
lh.addStaticHoliday ("17-FEB-1999", "Second Day of Lunar New Year");
lh.addStaticHoliday ("18-FEB-1999", "Third Day of Lunar New Year");
lh.addStaticHoliday ("05-APR-1999", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-1999", "May Day");
lh.addStaticHoliday ("18-JUN-1999", "Dragon Boat Festival");
lh.addStaticHoliday ("19-JUN-1999", "Bridging Day");
lh.addStaticHoliday ("01-JUL-1999", "Bank Holiday");
lh.addStaticHoliday ("24-SEP-1999", "Moon Festival Day");
lh.addStaticHoliday ("12-NOV-1999", "Sun Yat-Sens Birthday");
lh.addStaticHoliday ("31-DEC-1999", "Special Holiday");
lh.addStaticHoliday ("01-JAN-2000", "New Years Day");
lh.addStaticHoliday ("03-JAN-2000", "Bank Holiday Observed");
lh.addStaticHoliday ("04-FEB-2000", "Lunar New Years Eve");
lh.addStaticHoliday ("05-FEB-2000", "Lunar New Years Day");
lh.addStaticHoliday ("07-FEB-2000", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2000", "Memorial Day");
lh.addStaticHoliday ("18-MAR-2000", "Election Day");
lh.addStaticHoliday ("03-APR-2000", "Childrens Day");
lh.addStaticHoliday ("04-APR-2000", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2000", "May Day");
lh.addStaticHoliday ("06-JUN-2000", "Dragon Boat Festival");
lh.addStaticHoliday ("01-JUL-2000", "Bank Holiday");
lh.addStaticHoliday ("23-AUG-2000", "TYPHOON-OFFICE CLOSE");
lh.addStaticHoliday ("12-SEP-2000", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2000", "National Day");
lh.addStaticHoliday ("25-DEC-2000", "Constitution Day");
lh.addStaticHoliday ("01-JAN-2001", "New Years Day");
lh.addStaticHoliday ("22-JAN-2001", "Bridging Day");
lh.addStaticHoliday ("23-JAN-2001", "Lunar New Years Eve");
lh.addStaticHoliday ("24-JAN-2001", "Lunar New Years Day");
lh.addStaticHoliday ("25-JAN-2001", "Second Day of Lunar New Year");
lh.addStaticHoliday ("26-JAN-2001", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2001", "Memorial Day");
lh.addStaticHoliday ("05-APR-2001", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2001", "May Day");
lh.addStaticHoliday ("25-JUN-2001", "Dragon Boat Festival");
lh.addStaticHoliday ("30-JUL-2001", "TYPHOON-OFFICE CLOSE");
lh.addStaticHoliday ("17-SEP-2001", "TYPHOON-OFFICE CLOSE");
lh.addStaticHoliday ("18-SEP-2001", "TYPHOON-OFFICE CLOSE");
lh.addStaticHoliday ("01-OCT-2001", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2001", "National Day");
lh.addStaticHoliday ("01-JAN-2002", "New Years Day");
lh.addStaticHoliday ("11-FEB-2002", "Lunar New Years Eve");
lh.addStaticHoliday ("12-FEB-2002", "Lunar New Years Day");
lh.addStaticHoliday ("13-FEB-2002", "Second Day of Lunar New Year");
lh.addStaticHoliday ("14-FEB-2002", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2002", "MEMORIAL DAY");
lh.addStaticHoliday ("02-MAR-2002", "Special Holiday");
lh.addStaticHoliday ("05-APR-2002", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2002", "LABOR DAY");
lh.addStaticHoliday ("10-OCT-2002", "National Day");
lh.addStaticHoliday ("01-JAN-2003", "New Years Day");
lh.addStaticHoliday ("31-JAN-2003", "Lunar New Years Eve");
lh.addStaticHoliday ("03-FEB-2003", "Lunar New Years Day Observed");
lh.addStaticHoliday ("04-FEB-2003", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("05-FEB-2003", "Chinese New Year Holiday Period");
lh.addStaticHoliday ("28-FEB-2003", "Special Holiday");
lh.addStaticHoliday ("01-MAY-2003", "May Day");
lh.addStaticHoliday ("04-JUN-2003", "Dragon Boat Festival");
lh.addStaticHoliday ("11-SEP-2003", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2003", "National Day");
lh.addStaticHoliday ("01-JAN-2004", "New Years Day");
lh.addStaticHoliday ("21-JAN-2004", "Lunar New Years Eve");
lh.addStaticHoliday ("22-JAN-2004", "Lunar New Years Day");
lh.addStaticHoliday ("23-JAN-2004", "Second Day of Lunar New Year");
lh.addStaticHoliday ("26-JAN-2004", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("22-JUN-2004", "Dragon Boat Festival");
lh.addStaticHoliday ("24-AUG-2004", "Special Holiday");
lh.addStaticHoliday ("25-AUG-2004", "Special Holiday");
lh.addStaticHoliday ("28-SEP-2004", "Moon Festival Day");
lh.addStaticHoliday ("25-OCT-2004", "Special Holiday");
lh.addStaticHoliday ("07-FEB-2005", "Bridging Day");
lh.addStaticHoliday ("08-FEB-2005", "Lunar New Years Eve");
lh.addStaticHoliday ("09-FEB-2005", "Lunar New Years Day");
lh.addStaticHoliday ("10-FEB-2005", "Second Day of Lunar New Year");
lh.addStaticHoliday ("11-FEB-2005", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2005", "Memorial Day");
lh.addStaticHoliday ("05-APR-2005", "Tomb Sweeping Day");
lh.addStaticHoliday ("02-MAY-2005", "Labor Day Observed");
lh.addStaticHoliday ("18-JUL-2005", "Special Holiday");
lh.addStaticHoliday ("05-AUG-2005", "Special Holiday");
lh.addStaticHoliday ("01-SEP-2005", "Special Holiday");
lh.addStaticHoliday ("10-OCT-2005", "National Day");
lh.addStaticHoliday ("28-JAN-2006", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("29-JAN-2006", "Lunar New Years Day Observed");
lh.addStaticHoliday ("30-JAN-2006", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("31-JAN-2006", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("01-FEB-2006", "Lunar New Years Day Observed");
lh.addStaticHoliday ("02-FEB-2006", "Lunar New Years Day Observed");
lh.addStaticHoliday ("28-FEB-2006", "Memorial Day");
lh.addStaticHoliday ("05-APR-2006", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2006", "Labor Day Observed");
lh.addStaticHoliday ("31-MAY-2006", "Dragon Boat Festival");
lh.addStaticHoliday ("06-OCT-2006", "Moon Festival Day");
lh.addStaticHoliday ("09-OCT-2006", "Bank Holiday");
lh.addStaticHoliday ("10-OCT-2006", "National Day");
lh.addStaticHoliday ("01-JAN-2007", "New Years Day");
lh.addStaticHoliday ("19-FEB-2007", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("20-FEB-2007", "Lunar New Years Day Observed");
lh.addStaticHoliday ("21-FEB-2007", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("22-FEB-2007", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("23-FEB-2007", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2007", "Memorial Day");
lh.addStaticHoliday ("05-APR-2007", "Tomb Sweeping Day");
lh.addStaticHoliday ("06-APR-2007", "Bridging Day");
lh.addStaticHoliday ("01-MAY-2007", "May Day");
lh.addStaticHoliday ("18-JUN-2007", "Bridging Day");
lh.addStaticHoliday ("19-JUN-2007", "Dragon Boat Festival");
lh.addStaticHoliday ("18-SEP-2007", "Special Holiday");
lh.addStaticHoliday ("24-SEP-2007", "Bridging Day");
lh.addStaticHoliday ("25-SEP-2007", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2007", "National Day");
lh.addStaticHoliday ("01-JAN-2008", "New Years Day");
lh.addStaticHoliday ("06-FEB-2008", "Lunar New Years Eve");
lh.addStaticHoliday ("07-FEB-2008", "Lunar New Years Day");
lh.addStaticHoliday ("08-FEB-2008", "Second Day of Lunar New Year");
lh.addStaticHoliday ("11-FEB-2008", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2008", "Memorial Day");
lh.addStaticHoliday ("04-APR-2008", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2008", "May Day");
lh.addStaticHoliday ("28-JUL-2008", "Special Holiday");
lh.addStaticHoliday ("29-SEP-2008", "Special Holiday");
lh.addStaticHoliday ("10-OCT-2008", "National Day");
lh.addStaticHoliday ("01-JAN-2009", "New Years Day");
lh.addStaticHoliday ("02-JAN-2009", "Bridging Day");
lh.addStaticHoliday ("26-JAN-2009", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("27-JAN-2009", "Lunar New Years Day Observed");
lh.addStaticHoliday ("28-JAN-2009", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("29-JAN-2009", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("30-JAN-2009", "Bridging Day");
lh.addStaticHoliday ("01-MAY-2009", "May Day");
lh.addStaticHoliday ("28-MAY-2009", "Dragon Boat Festival");
lh.addStaticHoliday ("29-MAY-2009", "Dragon Boat Festival");
lh.addStaticHoliday ("07-AUG-2009", "Special Holiday");
lh.addStaticHoliday ("01-JAN-2010", "New Years Day");
lh.addStaticHoliday ("13-FEB-2010", "Chinese New Year");
lh.addStaticHoliday ("14-FEB-2010", "Chinese New Year");
lh.addStaticHoliday ("15-FEB-2010", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("16-FEB-2010", "Lunar New Years Day Observed");
lh.addStaticHoliday ("17-FEB-2010", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("18-FEB-2010", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("19-FEB-2010", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2010", "Peace Day");
lh.addStaticHoliday ("05-APR-2010", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2010", "Labour Day");
lh.addStaticHoliday ("16-JUN-2010", "Dragon Boat Festival");
lh.addStaticHoliday ("22-SEP-2010", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2010", "National Day");
lh.addStaticHoliday ("02-FEB-2011", "Lunar New Years Eve");
lh.addStaticHoliday ("03-FEB-2011", "Lunar New Years Day");
lh.addStaticHoliday ("04-FEB-2011", "Second Day of Lunar New Year");
lh.addStaticHoliday ("07-FEB-2011", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2011", "Memorial Day");
lh.addStaticHoliday ("04-APR-2011", "Childrens Day");
lh.addStaticHoliday ("05-APR-2011", "Tomb Sweeping Day");
lh.addStaticHoliday ("02-MAY-2011", "May Day Observed");
lh.addStaticHoliday ("06-JUN-2011", "Dragon Boat Festival");
lh.addStaticHoliday ("12-SEP-2011", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2011", "National Day");
lh.addStaticHoliday ("23-JAN-2012", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("24-JAN-2012", "Lunar New Years Day Observed");
lh.addStaticHoliday ("25-JAN-2012", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("26-JAN-2012", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("27-JAN-2012", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2012", "Memorial Day");
lh.addStaticHoliday ("03-APR-2012", "Childrens Day");
lh.addStaticHoliday ("04-APR-2012", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2012", "May Day");
lh.addStaticHoliday ("10-OCT-2012", "National Day");
lh.addStaticHoliday ("01-JAN-2013", "New Years Day");
lh.addStaticHoliday ("11-FEB-2013", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("12-FEB-2013", "Lunar New Years Day Observed");
lh.addStaticHoliday ("13-FEB-2013", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("14-FEB-2013", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("15-FEB-2013", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2013", "Memorial Day");
lh.addStaticHoliday ("03-APR-2013", "Childrens Day");
lh.addStaticHoliday ("04-APR-2013", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2013", "May Day");
lh.addStaticHoliday ("12-JUN-2013", "Dragon Boat Festival");
lh.addStaticHoliday ("19-SEP-2013", "Moon Festival Day");
lh.addStaticHoliday ("20-SEP-2013", "Bridging Day");
lh.addStaticHoliday ("10-OCT-2013", "National Day");
lh.addStaticHoliday ("01-JAN-2014", "New Years Day");
lh.addStaticHoliday ("30-JAN-2014", "Lunar New Years Eve");
lh.addStaticHoliday ("31-JAN-2014", "Lunar New Years Day");
lh.addStaticHoliday ("03-FEB-2014", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("04-FEB-2014", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2014", "Memorial Day");
lh.addStaticHoliday ("04-APR-2014", "Childrens Day");
lh.addStaticHoliday ("01-MAY-2014", "May Day");
lh.addStaticHoliday ("02-JUN-2014", "Dragon Boat Festival");
lh.addStaticHoliday ("08-SEP-2014", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2014", "National Day");
lh.addStaticHoliday ("01-JAN-2015", "New Years Day");
lh.addStaticHoliday ("18-FEB-2015", "Lunar New Years Eve");
lh.addStaticHoliday ("19-FEB-2015", "Lunar New Years Day");
lh.addStaticHoliday ("20-FEB-2015", "Second Day of Lunar New Year");
lh.addStaticHoliday ("23-FEB-2015", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("01-MAY-2015", "May Day");
lh.addStaticHoliday ("01-JAN-2016", "New Years Day");
lh.addStaticHoliday ("08-FEB-2016", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("09-FEB-2016", "Lunar New Years Day Observed");
lh.addStaticHoliday ("10-FEB-2016", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("11-FEB-2016", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("12-FEB-2016", "Bridging Day");
lh.addStaticHoliday ("04-APR-2016", "Tomb Sweeping Day");
lh.addStaticHoliday ("02-MAY-2016", "May Day Observed");
lh.addStaticHoliday ("09-JUN-2016", "Dragon Boat Festival");
lh.addStaticHoliday ("10-JUN-2016", "Bridging Day");
lh.addStaticHoliday ("15-SEP-2016", "Moon Festival Day");
lh.addStaticHoliday ("16-SEP-2016", "Bridging Day");
lh.addStaticHoliday ("10-OCT-2016", "National Day");
lh.addStaticHoliday ("27-JAN-2017", "Lunar New Years Eve");
lh.addStaticHoliday ("30-JAN-2017", "Lunar New Years Day Observed");
lh.addStaticHoliday ("31-JAN-2017", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("01-FEB-2017", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2017", "Memorial Day");
lh.addStaticHoliday ("03-APR-2017", "Childrens Day");
lh.addStaticHoliday ("04-APR-2017", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2017", "May Day");
lh.addStaticHoliday ("29-MAY-2017", "Bridging Day");
lh.addStaticHoliday ("30-MAY-2017", "Dragon Boat Festival");
lh.addStaticHoliday ("04-OCT-2017", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2017", "National Day");
lh.addStaticHoliday ("01-JAN-2018", "New Years Day");
lh.addStaticHoliday ("15-FEB-2018", "Lunar New Years Eve");
lh.addStaticHoliday ("16-FEB-2018", "Lunar New Years Day");
lh.addStaticHoliday ("19-FEB-2018", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("20-FEB-2018", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2018", "Memorial Day");
lh.addStaticHoliday ("04-APR-2018", "Childrens Day");
lh.addStaticHoliday ("05-APR-2018", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2018", "May Day");
lh.addStaticHoliday ("18-JUN-2018", "Dragon Boat Festival");
lh.addStaticHoliday ("24-SEP-2018", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2018", "National Day");
lh.addStaticHoliday ("01-JAN-2019", "New Years Day");
lh.addStaticHoliday ("04-FEB-2019", "Lunar New Years Eve");
lh.addStaticHoliday ("05-FEB-2019", "Lunar New Years Day");
lh.addStaticHoliday ("06-FEB-2019", "Second Day of Lunar New Year");
lh.addStaticHoliday ("07-FEB-2019", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2019", "Memorial Day");
lh.addStaticHoliday ("04-APR-2019", "Childrens Day");
lh.addStaticHoliday ("05-APR-2019", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2019", "May Day");
lh.addStaticHoliday ("07-JUN-2019", "Dragon Boat Festival");
lh.addStaticHoliday ("13-SEP-2019", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2019", "National Day");
lh.addStaticHoliday ("01-JAN-2020", "New Years Day");
lh.addStaticHoliday ("24-JAN-2020", "Lunar New Years Eve");
lh.addStaticHoliday ("27-JAN-2020", "Lunar New Years Day Observed");
lh.addStaticHoliday ("28-JAN-2020", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("29-JAN-2020", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2020", "Memorial Day");
lh.addStaticHoliday ("03-APR-2020", "Childrens Day");
lh.addStaticHoliday ("01-MAY-2020", "May Day");
lh.addStaticHoliday ("25-JUN-2020", "Dragon Boat Festival");
lh.addStaticHoliday ("26-JUN-2020", "Bridging Day");
lh.addStaticHoliday ("01-OCT-2020", "Moon Festival Day");
lh.addStaticHoliday ("02-OCT-2020", "Bridging Day");
lh.addStaticHoliday ("01-JAN-2021", "New Years Day");
lh.addStaticHoliday ("11-FEB-2021", "Lunar New Years Eve");
lh.addStaticHoliday ("12-FEB-2021", "Lunar New Years Day");
lh.addStaticHoliday ("15-FEB-2021", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("16-FEB-2021", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("14-JUN-2021", "Dragon Boat Festival");
lh.addStaticHoliday ("20-SEP-2021", "Bridging Day");
lh.addStaticHoliday ("21-SEP-2021", "Moon Festival Day");
lh.addStaticHoliday ("31-JAN-2022", "Lunar New Years Eve");
lh.addStaticHoliday ("01-FEB-2022", "Lunar New Years Day");
lh.addStaticHoliday ("02-FEB-2022", "Second Day of Lunar New Year");
lh.addStaticHoliday ("03-FEB-2022", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2022", "Memorial Day");
lh.addStaticHoliday ("04-APR-2022", "Childrens Day");
lh.addStaticHoliday ("05-APR-2022", "Tomb Sweeping Day");
lh.addStaticHoliday ("02-MAY-2022", "May Day Observed");
lh.addStaticHoliday ("03-JUN-2022", "Dragon Boat Festival");
lh.addStaticHoliday ("10-OCT-2022", "National Day");
lh.addStaticHoliday ("23-JAN-2023", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("24-JAN-2023", "Lunar New Years Day Observed");
lh.addStaticHoliday ("25-JAN-2023", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("26-JAN-2023", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("27-JAN-2023", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2023", "Memorial Day");
lh.addStaticHoliday ("04-APR-2023", "Childrens Day");
lh.addStaticHoliday ("05-APR-2023", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2023", "May Day");
lh.addStaticHoliday ("22-JUN-2023", "Dragon Boat Festival");
lh.addStaticHoliday ("23-JUN-2023", "Bridging Day");
lh.addStaticHoliday ("29-SEP-2023", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2023", "National Day");
lh.addStaticHoliday ("01-JAN-2024", "New Years Day");
lh.addStaticHoliday ("09-FEB-2024", "Lunar New Years Eve");
lh.addStaticHoliday ("12-FEB-2024", "Lunar New Years Day Observed");
lh.addStaticHoliday ("13-FEB-2024", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("14-FEB-2024", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2024", "Memorial Day");
lh.addStaticHoliday ("03-APR-2024", "Childrens Day");
lh.addStaticHoliday ("04-APR-2024", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2024", "May Day");
lh.addStaticHoliday ("10-JUN-2024", "Dragon Boat Festival");
lh.addStaticHoliday ("16-SEP-2024", "Bridging Day");
lh.addStaticHoliday ("17-SEP-2024", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2024", "National Day");
lh.addStaticHoliday ("01-JAN-2025", "New Years Day");
lh.addStaticHoliday ("27-JAN-2025", "Bridging Day");
lh.addStaticHoliday ("28-JAN-2025", "Lunar New Years Eve");
lh.addStaticHoliday ("29-JAN-2025", "Lunar New Years Day");
lh.addStaticHoliday ("30-JAN-2025", "Second Day of Lunar New Year");
lh.addStaticHoliday ("31-JAN-2025", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2025", "Memorial Day");
lh.addStaticHoliday ("03-APR-2025", "Childrens Day");
lh.addStaticHoliday ("04-APR-2025", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2025", "May Day");
lh.addStaticHoliday ("06-OCT-2025", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2025", "National Day");
lh.addStaticHoliday ("01-JAN-2026", "New Years Day");
lh.addStaticHoliday ("16-FEB-2026", "Lunar New Years Eve");
lh.addStaticHoliday ("17-FEB-2026", "Lunar New Years Day");
lh.addStaticHoliday ("18-FEB-2026", "Second Day of Lunar New Year");
lh.addStaticHoliday ("19-FEB-2026", "Third Day of Lunar New Year");
lh.addStaticHoliday ("01-MAY-2026", "May Day");
lh.addStaticHoliday ("19-JUN-2026", "Dragon Boat Festival");
lh.addStaticHoliday ("25-SEP-2026", "Moon Festival Day");
lh.addStaticHoliday ("01-JAN-2027", "New Years Day");
lh.addStaticHoliday ("05-FEB-2027", "Lunar New Years Eve");
lh.addStaticHoliday ("08-FEB-2027", "Lunar New Years Day Observed");
lh.addStaticHoliday ("09-FEB-2027", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("10-FEB-2027", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("05-APR-2027", "Tomb Sweeping Day");
lh.addStaticHoliday ("09-JUN-2027", "Dragon Boat Festival");
lh.addStaticHoliday ("15-SEP-2027", "Moon Festival Day");
lh.addStaticHoliday ("24-JAN-2028", "Bridging Day");
lh.addStaticHoliday ("25-JAN-2028", "Lunar New Years Eve");
lh.addStaticHoliday ("26-JAN-2028", "Lunar New Years Day");
lh.addStaticHoliday ("27-JAN-2028", "Second Day of Lunar New Year");
lh.addStaticHoliday ("28-JAN-2028", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2028", "Memorial Day");
lh.addStaticHoliday ("03-APR-2028", "Childrens Day");
lh.addStaticHoliday ("04-APR-2028", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2028", "May Day");
lh.addStaticHoliday ("02-OCT-2028", "Bridging Day");
lh.addStaticHoliday ("03-OCT-2028", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2028", "National Day");
lh.addStaticHoliday ("01-JAN-2029", "New Years Day");
lh.addStaticHoliday ("12-FEB-2029", "Lunar New Years Eve");
lh.addStaticHoliday ("13-FEB-2029", "Lunar New Years Day");
lh.addStaticHoliday ("14-FEB-2029", "Second Day of Lunar New Year");
lh.addStaticHoliday ("15-FEB-2029", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2029", "Memorial Day");
lh.addStaticHoliday ("03-APR-2029", "Childrens Day");
lh.addStaticHoliday ("04-APR-2029", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2029", "May Day");
lh.addStaticHoliday ("10-OCT-2029", "National Day");
lh.addStaticHoliday ("01-JAN-2030", "New Years Day");
lh.addStaticHoliday ("04-FEB-2030", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("05-FEB-2030", "Lunar New Years Day Observed");
lh.addStaticHoliday ("06-FEB-2030", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("07-FEB-2030", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("08-FEB-2030", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2030", "Memorial Day");
lh.addStaticHoliday ("04-APR-2030", "Childrens Day");
lh.addStaticHoliday ("05-APR-2030", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2030", "May Day");
lh.addStaticHoliday ("05-JUN-2030", "Dragon Boat Festival");
lh.addStaticHoliday ("12-SEP-2030", "Moon Festival Day");
lh.addStaticHoliday ("13-SEP-2030", "Bridging Day");
lh.addStaticHoliday ("10-OCT-2030", "National Day");
lh.addStaticHoliday ("01-JAN-2031", "New Years Day");
lh.addStaticHoliday ("22-JAN-2031", "Lunar New Years Eve");
lh.addStaticHoliday ("23-JAN-2031", "Lunar New Years Day");
lh.addStaticHoliday ("24-JAN-2031", "Second Day of Lunar New Year");
lh.addStaticHoliday ("27-JAN-2031", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2031", "Memorial Day");
lh.addStaticHoliday ("04-APR-2031", "Childrens Day");
lh.addStaticHoliday ("01-MAY-2031", "May Day");
lh.addStaticHoliday ("23-JUN-2031", "Bridging Day");
lh.addStaticHoliday ("24-JUN-2031", "Dragon Boat Festival");
lh.addStaticHoliday ("01-OCT-2031", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2031", "National Day");
lh.addStaticHoliday ("01-JAN-2032", "New Years Day");
lh.addStaticHoliday ("09-FEB-2032", "Bridging Day");
lh.addStaticHoliday ("10-FEB-2032", "Lunar New Years Eve");
lh.addStaticHoliday ("11-FEB-2032", "Lunar New Years Day");
lh.addStaticHoliday ("12-FEB-2032", "Second Day of Lunar New Year");
lh.addStaticHoliday ("13-FEB-2032", "Third Day of Lunar New Year");
lh.addStaticHoliday ("31-JAN-2033", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("01-FEB-2033", "Lunar New Years Day Observed");
lh.addStaticHoliday ("02-FEB-2033", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("03-FEB-2033", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("04-FEB-2033", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2033", "Memorial Day");
lh.addStaticHoliday ("04-APR-2033", "Tomb Sweeping Day");
lh.addStaticHoliday ("02-MAY-2033", "May Day Observed");
lh.addStaticHoliday ("01-JUN-2033", "Dragon Boat Festival");
lh.addStaticHoliday ("08-SEP-2033", "Moon Festival Day");
lh.addStaticHoliday ("09-SEP-2033", "Bridging Day");
lh.addStaticHoliday ("10-OCT-2033", "National Day");
lh.addStaticHoliday ("20-FEB-2034", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("21-FEB-2034", "Lunar New Years Day Observed");
lh.addStaticHoliday ("22-FEB-2034", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("23-FEB-2034", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("24-FEB-2034", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2034", "Memorial Day");
lh.addStaticHoliday ("04-APR-2034", "Childrens Day");
lh.addStaticHoliday ("05-APR-2034", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2034", "May Day");
lh.addStaticHoliday ("19-JUN-2034", "Bridging Day");
lh.addStaticHoliday ("20-JUN-2034", "Dragon Boat Festival");
lh.addStaticHoliday ("27-SEP-2034", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2034", "National Day");
lh.addStaticHoliday ("01-JAN-2035", "New Years Day");
lh.addStaticHoliday ("07-FEB-2035", "Lunar New Years Eve");
lh.addStaticHoliday ("08-FEB-2035", "Lunar New Years Day");
lh.addStaticHoliday ("09-FEB-2035", "Second Day of Lunar New Year");
lh.addStaticHoliday ("12-FEB-2035", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2035", "Memorial Day");
lh.addStaticHoliday ("04-APR-2035", "Childrens Day");
lh.addStaticHoliday ("05-APR-2035", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2035", "May Day");
lh.addStaticHoliday ("10-OCT-2035", "National Day");
lh.addStaticHoliday ("01-JAN-2036", "New Years Day");
lh.addStaticHoliday ("28-JAN-2036", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("29-JAN-2036", "Lunar New Years Day Observed");
lh.addStaticHoliday ("30-JAN-2036", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("31-JAN-2036", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("01-FEB-2036", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2036", "Memorial Day");
lh.addStaticHoliday ("03-APR-2036", "Childrens Day");
lh.addStaticHoliday ("04-APR-2036", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2036", "May Day");
lh.addStaticHoliday ("30-MAY-2036", "Dragon Boat Festival");
lh.addStaticHoliday ("10-OCT-2036", "National Day");
lh.addStaticHoliday ("01-JAN-2037", "New Years Day");
lh.addStaticHoliday ("16-FEB-2037", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("17-FEB-2037", "Lunar New Years Day Observed");
lh.addStaticHoliday ("18-FEB-2037", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("19-FEB-2037", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("20-FEB-2037", "Bridging Day");
lh.addStaticHoliday ("03-APR-2037", "Childrens Day");
lh.addStaticHoliday ("01-MAY-2037", "May Day");
lh.addStaticHoliday ("18-JUN-2037", "Dragon Boat Festival");
lh.addStaticHoliday ("19-JUN-2037", "Bridging Day");
lh.addStaticHoliday ("24-SEP-2037", "Moon Festival Day");
lh.addStaticHoliday ("25-SEP-2037", "Bridging Day");
lh.addStaticHoliday ("01-JAN-2038", "New Years Day");
lh.addStaticHoliday ("03-FEB-2038", "Lunar New Years Eve");
lh.addStaticHoliday ("04-FEB-2038", "Lunar New Years Day");
lh.addStaticHoliday ("05-FEB-2038", "Second Day of Lunar New Year");
lh.addStaticHoliday ("08-FEB-2038", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("05-APR-2038", "Tomb Sweeping Day");
lh.addStaticHoliday ("07-JUN-2038", "Dragon Boat Festival");
lh.addStaticHoliday ("13-SEP-2038", "Moon Festival Day");
lh.addStaticHoliday ("24-JAN-2039", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("25-JAN-2039", "Lunar New Years Day Observed");
lh.addStaticHoliday ("26-JAN-2039", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("27-JAN-2039", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-JAN-2039", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2039", "Memorial Day");
lh.addStaticHoliday ("04-APR-2039", "Childrens Day");
lh.addStaticHoliday ("05-APR-2039", "Tomb Sweeping Day");
lh.addStaticHoliday ("02-MAY-2039", "May Day Observed");
lh.addStaticHoliday ("27-MAY-2039", "Dragon Boat Festival");
lh.addStaticHoliday ("10-OCT-2039", "National Day");
lh.addStaticHoliday ("13-FEB-2040", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("14-FEB-2040", "Lunar New Years Day Observed");
lh.addStaticHoliday ("15-FEB-2040", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("16-FEB-2040", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("17-FEB-2040", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2040", "Memorial Day");
lh.addStaticHoliday ("03-APR-2040", "Childrens Day");
lh.addStaticHoliday ("04-APR-2040", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2040", "May Day");
lh.addStaticHoliday ("14-JUN-2040", "Dragon Boat Festival");
lh.addStaticHoliday ("15-JUN-2040", "Bridging Day");
lh.addStaticHoliday ("20-SEP-2040", "Moon Festival Day");
lh.addStaticHoliday ("21-SEP-2040", "Bridging Day");
lh.addStaticHoliday ("10-OCT-2040", "National Day");
lh.addStaticHoliday ("01-JAN-2041", "New Years Day");
lh.addStaticHoliday ("31-JAN-2041", "Lunar New Years Eve");
lh.addStaticHoliday ("01-FEB-2041", "Lunar New Years Day");
lh.addStaticHoliday ("04-FEB-2041", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("05-FEB-2041", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2041", "Memorial Day");
lh.addStaticHoliday ("03-APR-2041", "Childrens Day");
lh.addStaticHoliday ("04-APR-2041", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2041", "May Day");
lh.addStaticHoliday ("03-JUN-2041", "Dragon Boat Festival");
lh.addStaticHoliday ("09-SEP-2041", "Bridging Day");
lh.addStaticHoliday ("10-SEP-2041", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2041", "National Day");
lh.addStaticHoliday ("01-JAN-2042", "New Years Day");
lh.addStaticHoliday ("20-JAN-2042", "Bridging Day");
lh.addStaticHoliday ("21-JAN-2042", "Lunar New Years Eve");
lh.addStaticHoliday ("22-JAN-2042", "Lunar New Years Day");
lh.addStaticHoliday ("23-JAN-2042", "Second Day of Lunar New Year");
lh.addStaticHoliday ("24-JAN-2042", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2042", "Memorial Day");
lh.addStaticHoliday ("03-APR-2042", "Childrens Day");
lh.addStaticHoliday ("04-APR-2042", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2042", "May Day");
lh.addStaticHoliday ("10-OCT-2042", "National Day");
lh.addStaticHoliday ("01-JAN-2043", "New Years Day");
lh.addStaticHoliday ("09-FEB-2043", "Lunar New Years Eve");
lh.addStaticHoliday ("10-FEB-2043", "Lunar New Years Day");
lh.addStaticHoliday ("11-FEB-2043", "Second Day of Lunar New Year");
lh.addStaticHoliday ("12-FEB-2043", "Third Day of Lunar New Year");
lh.addStaticHoliday ("01-MAY-2043", "May Day");
lh.addStaticHoliday ("11-JUN-2043", "Dragon Boat Festival");
lh.addStaticHoliday ("12-JUN-2043", "Bridging Day");
lh.addStaticHoliday ("17-SEP-2043", "Moon Festival Day");
lh.addStaticHoliday ("18-SEP-2043", "Bridging Day");
lh.addStaticHoliday ("01-JAN-2044", "New Years Day");
lh.addStaticHoliday ("29-JAN-2044", "Lunar New Years Eve");
lh.addStaticHoliday ("01-FEB-2044", "Lunar New Years Day Observed");
lh.addStaticHoliday ("02-FEB-2044", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("03-FEB-2044", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("04-APR-2044", "Tomb Sweeping Day");
lh.addStaticHoliday ("02-MAY-2044", "May Day Observed");
lh.addStaticHoliday ("30-MAY-2044", "Bridging Day");
lh.addStaticHoliday ("31-MAY-2044", "Dragon Boat Festival");
lh.addStaticHoliday ("05-OCT-2044", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2044", "National Day");
lh.addStaticHoliday ("16-FEB-2045", "Lunar New Years Eve");
lh.addStaticHoliday ("17-FEB-2045", "Lunar New Years Day");
lh.addStaticHoliday ("20-FEB-2045", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("21-FEB-2045", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2045", "Memorial Day");
lh.addStaticHoliday ("03-APR-2045", "Childrens Day");
lh.addStaticHoliday ("04-APR-2045", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2045", "May Day");
lh.addStaticHoliday ("19-JUN-2045", "Dragon Boat Festival");
lh.addStaticHoliday ("25-SEP-2045", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2045", "National Day");
lh.addStaticHoliday ("01-JAN-2046", "New Years Day");
lh.addStaticHoliday ("05-FEB-2046", "Lunar New Years Eve");
lh.addStaticHoliday ("06-FEB-2046", "Lunar New Years Day");
lh.addStaticHoliday ("07-FEB-2046", "Second Day of Lunar New Year");
lh.addStaticHoliday ("08-FEB-2046", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2046", "Memorial Day");
lh.addStaticHoliday ("03-APR-2046", "Childrens Day");
lh.addStaticHoliday ("04-APR-2046", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2046", "May Day");
lh.addStaticHoliday ("08-JUN-2046", "Dragon Boat Festival");
lh.addStaticHoliday ("10-OCT-2046", "National Day");
lh.addStaticHoliday ("01-JAN-2047", "New Years Day");
lh.addStaticHoliday ("25-JAN-2047", "Lunar New Years Eve");
lh.addStaticHoliday ("28-JAN-2047", "Lunar New Years Day Observed");
lh.addStaticHoliday ("29-JAN-2047", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("30-JAN-2047", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2047", "Memorial Day");
lh.addStaticHoliday ("04-APR-2047", "Childrens Day");
lh.addStaticHoliday ("05-APR-2047", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2047", "May Day");
lh.addStaticHoliday ("29-MAY-2047", "Dragon Boat Festival");
lh.addStaticHoliday ("04-OCT-2047", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2047", "National Day");
lh.addStaticHoliday ("01-JAN-2048", "New Years Day");
lh.addStaticHoliday ("13-FEB-2048", "Lunar New Years Eve");
lh.addStaticHoliday ("14-FEB-2048", "Lunar New Years Day");
lh.addStaticHoliday ("17-FEB-2048", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("18-FEB-2048", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2048", "Memorial Day");
lh.addStaticHoliday ("03-APR-2048", "Childrens Day");
lh.addStaticHoliday ("01-MAY-2048", "May Day");
lh.addStaticHoliday ("15-JUN-2048", "Dragon Boat Festival");
lh.addStaticHoliday ("21-SEP-2048", "Bridging Day");
lh.addStaticHoliday ("22-SEP-2048", "Moon Festival Day");
lh.addStaticHoliday ("01-JAN-2049", "New Years Day");
lh.addStaticHoliday ("01-FEB-2049", "Lunar New Years Eve");
lh.addStaticHoliday ("02-FEB-2049", "Lunar New Years Day");
lh.addStaticHoliday ("03-FEB-2049", "Second Day of Lunar New Year");
lh.addStaticHoliday ("04-FEB-2049", "Third Day of Lunar New Year");
lh.addStaticHoliday ("04-JUN-2049", "Dragon Boat Festival");
lh.addStaticHoliday ("24-JAN-2050", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("25-JAN-2050", "Lunar New Years Day Observed");
lh.addStaticHoliday ("26-JAN-2050", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("27-JAN-2050", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-JAN-2050", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2050", "Memorial Day");
lh.addStaticHoliday ("04-APR-2050", "Tomb Sweeping Day");
lh.addStaticHoliday ("02-MAY-2050", "May Day Observed");
lh.addStaticHoliday ("23-JUN-2050", "Dragon Boat Festival");
lh.addStaticHoliday ("24-JUN-2050", "Bridging Day");
lh.addStaticHoliday ("30-SEP-2050", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2050", "National Day");
lh.addStaticHoliday ("10-FEB-2051", "Lunar New Years Eve");
lh.addStaticHoliday ("13-FEB-2051", "Lunar New Years Day Observed");
lh.addStaticHoliday ("14-FEB-2051", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("15-FEB-2051", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2051", "Memorial Day");
lh.addStaticHoliday ("04-APR-2051", "Childrens Day");
lh.addStaticHoliday ("05-APR-2051", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2051", "May Day");
lh.addStaticHoliday ("12-JUN-2051", "Bridging Day");
lh.addStaticHoliday ("13-JUN-2051", "Dragon Boat Festival");
lh.addStaticHoliday ("18-SEP-2051", "Bridging Day");
lh.addStaticHoliday ("19-SEP-2051", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2051", "National Day");
lh.addStaticHoliday ("01-JAN-2052", "New Years Day");
lh.addStaticHoliday ("31-JAN-2052", "Lunar New Years Eve");
lh.addStaticHoliday ("01-FEB-2052", "Lunar New Years Day");
lh.addStaticHoliday ("02-FEB-2052", "Second Day of Lunar New Year");
lh.addStaticHoliday ("05-FEB-2052", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2052", "Memorial Day");
lh.addStaticHoliday ("03-APR-2052", "Childrens Day");
lh.addStaticHoliday ("04-APR-2052", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2052", "May Day");
lh.addStaticHoliday ("10-OCT-2052", "National Day");
lh.addStaticHoliday ("01-JAN-2053", "New Years Day");
lh.addStaticHoliday ("17-FEB-2053", "Bridging Day");
lh.addStaticHoliday ("18-FEB-2053", "Lunar New Years Eve");
lh.addStaticHoliday ("19-FEB-2053", "Lunar New Years Day");
lh.addStaticHoliday ("20-FEB-2053", "Second Day of Lunar New Year");
lh.addStaticHoliday ("21-FEB-2053", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2053", "Memorial Day");
lh.addStaticHoliday ("03-APR-2053", "Childrens Day");
lh.addStaticHoliday ("04-APR-2053", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2053", "May Day");
lh.addStaticHoliday ("20-JUN-2053", "Dragon Boat Festival");
lh.addStaticHoliday ("26-SEP-2053", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2053", "National Day");
lh.addStaticHoliday ("01-JAN-2054", "New Years Day");
lh.addStaticHoliday ("09-FEB-2054", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("10-FEB-2054", "Lunar New Years Day Observed");
lh.addStaticHoliday ("11-FEB-2054", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("12-FEB-2054", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("13-FEB-2054", "Bridging Day");
lh.addStaticHoliday ("03-APR-2054", "Childrens Day");
lh.addStaticHoliday ("01-MAY-2054", "May Day");
lh.addStaticHoliday ("10-JUN-2054", "Dragon Boat Festival");
lh.addStaticHoliday ("16-SEP-2054", "Moon Festival Day");
lh.addStaticHoliday ("01-JAN-2055", "New Years Day");
lh.addStaticHoliday ("27-JAN-2055", "Lunar New Years Eve");
lh.addStaticHoliday ("28-JAN-2055", "Lunar New Years Day");
lh.addStaticHoliday ("29-JAN-2055", "Second Day of Lunar New Year");
lh.addStaticHoliday ("01-FEB-2055", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("05-APR-2055", "Tomb Sweeping Day");
lh.addStaticHoliday ("04-OCT-2055", "Bridging Day");
lh.addStaticHoliday ("05-OCT-2055", "Moon Festival Day");
lh.addStaticHoliday ("14-FEB-2056", "Lunar New Years Eve");
lh.addStaticHoliday ("15-FEB-2056", "Lunar New Years Day");
lh.addStaticHoliday ("16-FEB-2056", "Second Day of Lunar New Year");
lh.addStaticHoliday ("17-FEB-2056", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2056", "Memorial Day");
lh.addStaticHoliday ("03-APR-2056", "Childrens Day");
lh.addStaticHoliday ("04-APR-2056", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2056", "May Day");
lh.addStaticHoliday ("10-OCT-2056", "National Day");
lh.addStaticHoliday ("01-JAN-2057", "New Years Day");
lh.addStaticHoliday ("05-FEB-2057", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("06-FEB-2057", "Lunar New Years Day Observed");
lh.addStaticHoliday ("07-FEB-2057", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("08-FEB-2057", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("09-FEB-2057", "Bridging Day");
lh.addStaticHoliday ("28-FEB-2057", "Memorial Day");
lh.addStaticHoliday ("03-APR-2057", "Childrens Day");
lh.addStaticHoliday ("04-APR-2057", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2057", "May Day");
lh.addStaticHoliday ("06-JUN-2057", "Dragon Boat Festival");
lh.addStaticHoliday ("13-SEP-2057", "Moon Festival Day");
lh.addStaticHoliday ("14-SEP-2057", "Bridging Day");
lh.addStaticHoliday ("10-OCT-2057", "National Day");
lh.addStaticHoliday ("01-JAN-2058", "New Years Day");
lh.addStaticHoliday ("23-JAN-2058", "Lunar New Years Eve");
lh.addStaticHoliday ("24-JAN-2058", "Lunar New Years Day");
lh.addStaticHoliday ("25-JAN-2058", "Second Day of Lunar New Year");
lh.addStaticHoliday ("28-JAN-2058", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2058", "Memorial Day");
lh.addStaticHoliday ("03-APR-2058", "Childrens Day");
lh.addStaticHoliday ("04-APR-2058", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2058", "May Day");
lh.addStaticHoliday ("24-JUN-2058", "Bridging Day");
lh.addStaticHoliday ("25-JUN-2058", "Dragon Boat Festival");
lh.addStaticHoliday ("02-OCT-2058", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2058", "National Day");
lh.addStaticHoliday ("01-JAN-2059", "New Years Day");
lh.addStaticHoliday ("10-FEB-2059", "Bridging Day");
lh.addStaticHoliday ("11-FEB-2059", "Lunar New Years Eve");
lh.addStaticHoliday ("12-FEB-2059", "Lunar New Years Day");
lh.addStaticHoliday ("13-FEB-2059", "Second Day of Lunar New Year");
lh.addStaticHoliday ("14-FEB-2059", "Third Day of Lunar New Year");
lh.addStaticHoliday ("28-FEB-2059", "Memorial Day");
lh.addStaticHoliday ("04-APR-2059", "Childrens Day");
lh.addStaticHoliday ("01-MAY-2059", "May Day");
lh.addStaticHoliday ("10-OCT-2059", "National Day");
lh.addStaticHoliday ("01-JAN-2060", "New Years Day");
lh.addStaticHoliday ("02-FEB-2060", "Lunar New Years Eve Observed");
lh.addStaticHoliday ("03-FEB-2060", "Lunar New Years Day Observed");
lh.addStaticHoliday ("04-FEB-2060", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("05-FEB-2060", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("06-FEB-2060", "Bridging Day");
lh.addStaticHoliday ("03-JUN-2060", "Dragon Boat Festival");
lh.addStaticHoliday ("04-JUN-2060", "Bridging Day");
lh.addStaticHoliday ("09-SEP-2060", "Moon Festival Day");
lh.addStaticHoliday ("10-SEP-2060", "Bridging Day");
lh.addStaticHoliday ("20-JAN-2061", "Lunar New Years Eve");
lh.addStaticHoliday ("21-JAN-2061", "Lunar New Years Day");
lh.addStaticHoliday ("24-JAN-2061", "Second Day of Lunar New Year Observed");
lh.addStaticHoliday ("25-JAN-2061", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2061", "Memorial Day");
lh.addStaticHoliday ("04-APR-2061", "Tomb Sweeping Day");
lh.addStaticHoliday ("02-MAY-2061", "May Day Observed");
lh.addStaticHoliday ("22-JUN-2061", "Dragon Boat Festival");
lh.addStaticHoliday ("28-SEP-2061", "Moon Festival Day");
lh.addStaticHoliday ("10-OCT-2061", "National Day");
lh.addStaticHoliday ("08-FEB-2062", "Lunar New Years Eve");
lh.addStaticHoliday ("09-FEB-2062", "Lunar New Years Day");
lh.addStaticHoliday ("10-FEB-2062", "Second Day of Lunar New Year");
lh.addStaticHoliday ("13-FEB-2062", "Third Day of Lunar New Year Observed");
lh.addStaticHoliday ("28-FEB-2062", "Memorial Day");
lh.addStaticHoliday ("03-APR-2062", "Childrens Day");
lh.addStaticHoliday ("04-APR-2062", "Tomb Sweeping Day");
lh.addStaticHoliday ("01-MAY-2062", "May Day");
lh.addStaticHoliday ("10-OCT-2062", "National Day");
lh.addStandardWeekend();
return lh;
}
}
| apache-2.0 |
yuyupapa/OpenSource | scouter.client/src/scouter/client/counter/actions/OpenPastTimeGroupTotalViewAction.java | 2065 | /*
* Copyright 2015 the original author or authors.
* @https://github.com/scouter-project/scouter
*
* 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 scouter.client.counter.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import scouter.client.Images;
import scouter.client.group.view.CounterPastTimeGroupTotalView;
import scouter.client.model.GroupObject;
import scouter.client.util.ConsoleProxy;
import scouter.client.util.ImageUtil;
import scouter.client.util.TimeUtil;
public class OpenPastTimeGroupTotalViewAction extends Action {
public final static String ID = OpenPastTimeGroupTotalViewAction.class.getName();
private final IWorkbenchWindow window;
private String grpName;
private String objType;
private String counter;
public OpenPastTimeGroupTotalViewAction(IWorkbenchWindow window, String label, String counter, GroupObject grpObj) {
this.window = window;
this.counter = counter;
this.grpName = grpObj.getName();
this.objType = grpObj.getObjType();
setText(label);
setId(ID);
setImageDescriptor(ImageUtil.getImageDescriptor(Images.sum));
}
public void run() {
if (window != null) {
try {
window.getActivePage().showView(
CounterPastTimeGroupTotalView.ID, grpName + "&" + objType + "&" + counter + "&" + TimeUtil.getCurrentTime(),
IWorkbenchPage.VIEW_ACTIVATE);
} catch (PartInitException e) {
ConsoleProxy.error(e.toString());
}
}
}
}
| apache-2.0 |
apache/jackrabbit-ocm | src/test/java/org/apache/jackrabbit/ocm/NodeUtilTest.java | 3010 | /*
* 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.jackrabbit.ocm;
import junit.framework.TestCase;
import org.apache.jackrabbit.ocm.repository.NodeUtil;
/** Testcase for RepositoryUtil.
*
* @author <a href="mailto:christophe.lombart@sword-technologies.com">Christophe Lombart</a>
* @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>
*/
public class NodeUtilTest extends TestCase
{
public NodeUtilTest(String testName)
{
super(testName);
}
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception
{
super.setUp();
}
/**
* @see junit.framework.TestCase#tearDown()
*/
public void tearDown() throws Exception
{
super.tearDown();
}
/**
* Test for getParentPath()
*
*/
public void testGetParentPath()
{
try
{
String parentPath = NodeUtil.getParentPath("/test");
assertNotNull("parent path is null for /test", parentPath);
assertTrue("parent path is incorrect for /test", parentPath.equals("/"));
parentPath = NodeUtil.getParentPath("/test/test2");
assertNotNull("parent path is null for /test/test2", parentPath);
assertTrue("parent path is incorrect for /test/test2", parentPath.equals("/test"));
}
catch (Exception e)
{
e.printStackTrace();
fail("Unable to find the repository : " + e);
}
}
/**
* Test for getNodeName()
*
*/
public void testGetNodeName()
{
try
{
String nodeName = NodeUtil.getNodeName("/test");
assertNotNull("node name is null for /test", nodeName);
assertTrue("node name is incorrect for /test", nodeName.equals("test"));
nodeName = NodeUtil.getNodeName("/test/test2");
assertNotNull("node name is null for /test/test2", nodeName);
assertTrue("node name is incorrect for /test/test2", nodeName.equals("test2"));
}
catch (Exception e)
{
e.printStackTrace();
fail("Unable to find the repository : " + e);
}
}
} | apache-2.0 |
rashidaligee/kylo | metadata/metadata-api/src/main/java/com/thinkbiganalytics/metadata/api/feed/InitializationStatus.java | 1375 | /**
*
*/
package com.thinkbiganalytics.metadata.api.feed;
/*-
* #%L
* thinkbig-metadata-api
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
/**
*
*/
public class InitializationStatus {
private final State state;
private final DateTime timestamp;
public InitializationStatus(State state) {
this(state, DateTime.now(DateTimeZone.UTC));
}
public InitializationStatus(State state, DateTime timestamp) {
super();
this.state = state;
this.timestamp = timestamp;
}
public State getState() {
return state;
}
public DateTime getTimestamp() {
return timestamp;
}
public enum State {
PENDING, IN_PROGRESS, SUCCESS, FAILED
}
}
| apache-2.0 |
rmichela/grpc-java | interop-testing/src/test/java/io/grpc/ChannelAndServerBuilderTest.java | 3625 | /*
* Copyright 2017, gRPC Authors 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 io.grpc;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo;
import com.google.common.truth.Truth;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Assume;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
/**
* Tests that Channel and Server builders properly hide the static constructors.
*/
@RunWith(Parameterized.class)
public class ChannelAndServerBuilderTest {
@Parameter
public Class<?> builderClass;
/**
* Javadoc.
*/
@Parameters(name = "class={0}")
public static Collection<Object[]> params() throws Exception {
ClassLoader loader = ChannelAndServerBuilderTest.class.getClassLoader();
List<Object[]> classes = new ArrayList<Object[]>();
for (ClassInfo classInfo : ClassPath.from(loader).getTopLevelClassesRecursive("io.grpc")) {
Class<?> clazz = Class.forName(classInfo.getName(), false /*initialize*/, loader);
if (ServerBuilder.class.isAssignableFrom(clazz) && clazz != ServerBuilder.class) {
classes.add(new Object[]{clazz});
} else if (ManagedChannelBuilder.class.isAssignableFrom(clazz)
&& clazz != ManagedChannelBuilder.class ) {
classes.add(new Object[]{clazz});
}
}
Truth.assertWithMessage("Unable to find any builder classes").that(classes).isNotEmpty();
return classes;
}
@Test
public void serverBuilderHidesMethod_forPort() throws Exception {
Assume.assumeTrue(ServerBuilder.class.isAssignableFrom(builderClass));
Method method = builderClass.getMethod("forPort", int.class);
assertTrue(Modifier.isStatic(method.getModifiers()));
assertTrue(ServerBuilder.class.isAssignableFrom(method.getReturnType()));
assertSame(builderClass, method.getDeclaringClass());
}
@Test
public void channelBuilderHidesMethod_forAddress() throws Exception {
Assume.assumeTrue(ManagedChannelBuilder.class.isAssignableFrom(builderClass));
Method method = builderClass.getMethod("forAddress", String.class, int.class);
assertTrue(Modifier.isStatic(method.getModifiers()));
assertTrue(ManagedChannelBuilder.class.isAssignableFrom(method.getReturnType()));
assertSame(builderClass, method.getDeclaringClass());
}
@Test
public void channelBuilderHidesMethod_forTarget() throws Exception {
Assume.assumeTrue(ManagedChannelBuilder.class.isAssignableFrom(builderClass));
Method method = builderClass.getMethod("forTarget", String.class);
assertTrue(Modifier.isStatic(method.getModifiers()));
assertTrue(ManagedChannelBuilder.class.isAssignableFrom(method.getReturnType()));
assertSame(builderClass, method.getDeclaringClass());
}
}
| apache-2.0 |
thc202/zap-extensions | addOns/exim/src/main/java/org/zaproxy/addon/exim/har/MenuImportHar.java | 4914 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2021 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.addon.exim.har;
import edu.umass.cs.benchlab.har.tools.HarFileReader;
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.view.View;
import org.zaproxy.addon.commonlib.ui.ProgressPane;
import org.zaproxy.addon.commonlib.ui.ProgressPaneListener;
import org.zaproxy.addon.commonlib.ui.ReadableFileChooser;
import org.zaproxy.addon.exim.ExtensionExim;
import org.zaproxy.zap.view.ZapMenuItem;
public class MenuImportHar extends ZapMenuItem {
private static final long serialVersionUID = -9207224834749823025L;
private static final Logger LOG = LogManager.getLogger(MenuImportHar.class);
private static final String THREAD_PREFIX = "ZAP-Import-Har-";
private int threadId = 1;
public MenuImportHar() {
super("exim.har.topmenu.import.importhar");
this.setToolTipText(
Constant.messages.getString("exim.har.topmenu.import.importhar.tooltip"));
this.addActionListener(
e -> {
JFileChooser chooser =
new ReadableFileChooser(
Model.getSingleton().getOptionsParam().getUserDirectory());
int rc = chooser.showOpenDialog(View.getSingleton().getMainFrame());
if (rc == JFileChooser.APPROVE_OPTION) {
Thread t =
new Thread() {
@Override
public void run() {
this.setName(THREAD_PREFIX + threadId++);
File file = chooser.getSelectedFile();
ProgressPane currentImportPane =
new ProgressPane(file.getAbsolutePath());
int tasks = 0;
try {
tasks =
new HarFileReader()
.readHarFile(file)
.getEntries()
.getEntries()
.size();
} catch (IOException e) {
LOG.warn(
"Couldn't count entries in: {}",
file.getAbsoluteFile());
}
currentImportPane.setTotalTasks(tasks);
ExtensionExim.getProgressPanel()
.addProgressPane(currentImportPane);
HarImporter harImporter =
new HarImporter(
file,
new ProgressPaneListener(
currentImportPane));
if (!harImporter.isSuccess()) {
View.getSingleton()
.showWarningDialog(
Constant.messages.getString(
"exim.har.file.import.error",
file.getAbsolutePath()));
}
}
};
t.start();
}
});
}
}
| apache-2.0 |
gingerwizard/elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/preprocessing/TargetMeanEncoding.java | 8304 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.core.ml.inference.preprocessing;
import org.apache.lucene.util.RamUsageEstimator;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* PreProcessor for target mean encoding a set of categorical values for a given field.
*/
public class TargetMeanEncoding implements LenientlyParsedPreProcessor, StrictlyParsedPreProcessor {
public static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(TargetMeanEncoding.class);
public static final ParseField NAME = new ParseField("target_mean_encoding");
public static final ParseField FIELD = new ParseField("field");
public static final ParseField FEATURE_NAME = new ParseField("feature_name");
public static final ParseField TARGET_MAP = new ParseField("target_map");
public static final ParseField DEFAULT_VALUE = new ParseField("default_value");
public static final ParseField CUSTOM = new ParseField("custom");
private static final ConstructingObjectParser<TargetMeanEncoding, PreProcessorParseContext> STRICT_PARSER = createParser(false);
private static final ConstructingObjectParser<TargetMeanEncoding, PreProcessorParseContext> LENIENT_PARSER = createParser(true);
@SuppressWarnings("unchecked")
private static ConstructingObjectParser<TargetMeanEncoding, PreProcessorParseContext> createParser(boolean lenient) {
ConstructingObjectParser<TargetMeanEncoding, PreProcessorParseContext> parser = new ConstructingObjectParser<>(
NAME.getPreferredName(),
lenient,
(a, c) -> new TargetMeanEncoding((String)a[0],
(String)a[1],
(Map<String, Double>)a[2],
(Double)a[3],
a[4] == null ? c.isCustomByDefault() : (Boolean)a[4]));
parser.declareString(ConstructingObjectParser.constructorArg(), FIELD);
parser.declareString(ConstructingObjectParser.constructorArg(), FEATURE_NAME);
parser.declareObject(ConstructingObjectParser.constructorArg(),
(p, c) -> p.map(HashMap::new, XContentParser::doubleValue),
TARGET_MAP);
parser.declareDouble(ConstructingObjectParser.constructorArg(), DEFAULT_VALUE);
parser.declareBoolean(ConstructingObjectParser.optionalConstructorArg(), CUSTOM);
return parser;
}
public static TargetMeanEncoding fromXContentStrict(XContentParser parser, PreProcessorParseContext context) {
return STRICT_PARSER.apply(parser, context == null ? PreProcessorParseContext.DEFAULT : context);
}
public static TargetMeanEncoding fromXContentLenient(XContentParser parser, PreProcessorParseContext context) {
return LENIENT_PARSER.apply(parser, context == null ? PreProcessorParseContext.DEFAULT : context);
}
private final String field;
private final String featureName;
private final Map<String, Double> meanMap;
private final double defaultValue;
private final boolean custom;
public TargetMeanEncoding(String field, String featureName, Map<String, Double> meanMap, Double defaultValue, Boolean custom) {
this.field = ExceptionsHelper.requireNonNull(field, FIELD);
this.featureName = ExceptionsHelper.requireNonNull(featureName, FEATURE_NAME);
this.meanMap = Collections.unmodifiableMap(ExceptionsHelper.requireNonNull(meanMap, TARGET_MAP));
this.defaultValue = ExceptionsHelper.requireNonNull(defaultValue, DEFAULT_VALUE);
this.custom = custom == null ? false : custom;
}
public TargetMeanEncoding(StreamInput in) throws IOException {
this.field = in.readString();
this.featureName = in.readString();
this.meanMap = Collections.unmodifiableMap(in.readMap(StreamInput::readString, StreamInput::readDouble));
this.defaultValue = in.readDouble();
this.custom = in.readBoolean();
}
/**
* @return Field name on which to target mean encode
*/
public String getField() {
return field;
}
/**
* @return Map of Value: targetMean for the target mean encoding
*/
public Map<String, Double> getMeanMap() {
return meanMap;
}
/**
* @return The default value to set when a previously unobserved value is seen
*/
public Double getDefaultValue() {
return defaultValue;
}
/**
* @return The feature name for the encoded value
*/
public String getFeatureName() {
return featureName;
}
@Override
public Map<String, String> reverseLookup() {
return Collections.singletonMap(featureName, field);
}
@Override
public boolean isCustom() {
return custom;
}
@Override
public String getOutputFieldType(String outputField) {
return NumberFieldMapper.NumberType.DOUBLE.typeName();
}
@Override
public String getName() {
return NAME.getPreferredName();
}
@Override
public List<String> inputFields() {
return Collections.singletonList(field);
}
@Override
public List<String> outputFields() {
return Collections.singletonList(featureName);
}
@Override
public void process(Map<String, Object> fields) {
Object value = fields.get(field);
if (value == null) {
return;
}
fields.put(featureName, meanMap.getOrDefault(value.toString(), defaultValue));
}
@Override
public String getWriteableName() {
return NAME.getPreferredName();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(field);
out.writeString(featureName);
out.writeMap(meanMap, StreamOutput::writeString, StreamOutput::writeDouble);
out.writeDouble(defaultValue);
out.writeBoolean(custom);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(FIELD.getPreferredName(), field);
builder.field(FEATURE_NAME.getPreferredName(), featureName);
builder.field(TARGET_MAP.getPreferredName(), meanMap);
builder.field(DEFAULT_VALUE.getPreferredName(), defaultValue);
builder.field(CUSTOM.getPreferredName(), custom);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TargetMeanEncoding that = (TargetMeanEncoding) o;
return Objects.equals(field, that.field)
&& Objects.equals(featureName, that.featureName)
&& Objects.equals(meanMap, that.meanMap)
&& Objects.equals(defaultValue, that.defaultValue)
&& Objects.equals(custom, that.custom);
}
@Override
public int hashCode() {
return Objects.hash(field, featureName, meanMap, defaultValue, custom);
}
@Override
public long ramBytesUsed() {
long size = SHALLOW_SIZE;
size += RamUsageEstimator.sizeOf(field);
size += RamUsageEstimator.sizeOf(featureName);
// defSize:0 indicates that there is not a defined size. Finding the shallowSize of Double gives the best estimate
size += RamUsageEstimator.sizeOfMap(meanMap, 0);
return size;
}
@Override
public String toString() {
return Strings.toString(this);
}
}
| apache-2.0 |
zouzhberk/ambaridemo | demo-server/src/main/java/org/apache/ambari/server/actionmanager/ActionType.java | 1175 | /**
* 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.ambari.server.actionmanager;
/**
* Defines various action types
*/
public enum ActionType {
DISABLED, // Action cannot be executed
SYSTEM, // System defined
USER, // User defined
SYSTEM_REQUIRES_ADMIN, // Requires admin privileges
USER_REQUIRES_ADMIN, // Requires admin privileges
SYSTEM_DISABLED; // Ambari has disabled the action
}
| apache-2.0 |
lihongqiang/kettle-4.4.0-stable | src-plugins/kettle-gpload-plugin/src/org/pentaho/di/trans/steps/gpload/GPLoadMeta.java | 35939 | /* Copyright (c) 2011 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.*/
package org.pentaho.di.trans.steps.gpload;
import java.util.List;
import java.util.Map;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.SQLStatement;
import org.pentaho.di.core.annotations.Step;
import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.shared.SharedObjectInterface;
import org.pentaho.di.trans.DatabaseImpact;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.w3c.dom.Node;
/**
* GPLoad Bulk Loader Step Meta
*
* @author Matt Casters, Sean Flatley
*/
@Step(id = "GPLoad", image = "GBL.png", i18nPackageName="org.pentaho.di.trans.steps.gpload", name="GPLoad.TypeLongDesc", description = "GPLoad.TypeLongDesc", categoryDescription="i18n:org.pentaho.di.trans.step:BaseStep.Category.Bulk")
public class GPLoadMeta extends BaseStepMeta implements StepMetaInterface
{
private static Class<?> PKG = GPLoadMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
/** Collection of Local hosts **/
private String localHosts[];
/** LocalHostPort **/
private String localhostPort;
/** what's the schema for the target? */
private String schemaName;
/** what's the table for the target? */
private String tableName;
/** what's the target of the error table? */
private String errorTableName;
/** Path to the gpload utility */
private String gploadPath;
/** Path to the control file */
private String controlFile;
/** Path to the data file */
private String dataFile;
/** Path to the log file */
private String logFile;
/** database connection */
private DatabaseMeta databaseMeta;
/** Specified database field */
private String fieldTable[];
/** Field name in the stream */
private String fieldStream[];
/** Database column to match on for an update or merge operation */
private boolean matchColumn[];
/** Database columns to update */
private boolean updateColumn[];
/** the date mask to use if the value is a date */
private String dateMask[];
/** maximum errors */
private String maxErrors;
/** Load method */
private String loadMethod;
/** Load action */
private String loadAction;
/** Encoding to use */
private String encoding;
/** Erase files after use */
private boolean eraseFiles;
/** Boolean to indicate that numbers are to be enclosed */
private boolean encloseNumbers;
/** Data file delimiter */
private String delimiter;
/** Default number of maximum errors allowed on a load */
public static String MAX_ERRORS_DEFAULT = "50";
/** Update condition **/
private String updateCondition;
/*
* Encodings supported by GPLoad.
* This list was obtained from the GPAAdminGuide.
*/
public final static String[] SUPPORTED_ENCODINGS = {
"", "BIG5",
"EUC_CN", "EUC_JP", "EUC_KR", "EUC_TW",
"GB18030", "GBK",
"ISO-8859-1", "ISO_8859_5", "ISO_8859_6", "ISO_8859_7", "ISO_8859_8",
"JOHAB", "KOI8",
"LATIN1", "LATIN2", "LATIN3", "LATIN4", "LATIN5",
"LATIN6", "LATIN7", "LATIN8", "LATIN9", "LATIN10",
"MULE_INTERNAL", "SJIS", "SQL_ASCII", "UHC", "UTF8",
"WIN866", "WIN874", "WIN1250", "WIN1251", "WIN1252",
"WIN1253", "WIN1254", "WIN1255", "WIN1256", "WIN1257", "WIN1258" }; //$NON-NLS-1$
/*
* Do not translate following values!!! They are will end up in the job export.
*/
final static public String ACTION_INSERT = "insert";
final static public String ACTION_UPDATE = "update";
final static public String ACTION_MERGE = "merge";
/*
* Do not translate following values!!! They are will end up in the job export.
*/
// final static public String METHOD_AUTO_CONCURRENT = "AUTO_CONCURRENT";
final static public String METHOD_AUTO_END = "AUTO_END";
final static public String METHOD_MANUAL = "MANUAL";
/*
* Do not translate following values!!! They are will end up in the job export.
*/
final static public String DATE_MASK_DATE = "DATE";
final static public String DATE_MASK_DATETIME = "DATETIME";
public GPLoadMeta()
{
super();
}
/**
* @return Returns the database.
*/
public DatabaseMeta getDatabaseMeta()
{
return databaseMeta;
}
/**
* @param database The database to set.
*/
public void setDatabaseMeta(DatabaseMeta database)
{
this.databaseMeta = database;
}
/**
* @return Returns the tableName.
*/
public String getTableName()
{
return tableName;
}
/**
* @param tableName The tableName to set.
*/
public void setTableName(String tableName)
{
this.tableName = tableName;
}
/**
* @return Returns the errorTableName.
*/
public String getErrorTableName()
{
return errorTableName;
}
/**
* @param errorTableName The error table name to set.
*/
public void setErrorTableName(String errorTableName)
{
this.errorTableName = errorTableName;
}
public String getGploadPath() {
return gploadPath;
}
public void setGploadPath(String gploadPath) {
this.gploadPath = gploadPath;
}
/**
* @return Returns the fieldTable.
*/
public String[] getFieldTable()
{
return fieldTable;
}
/**
* @param fieldTable The fieldTable to set.
*/
public void setFieldTable(String[] fieldTable)
{
this.fieldTable = fieldTable;
}
/**
* @return Returns the fieldStream.
*/
public String[] getFieldStream()
{
return fieldStream;
}
/**
* @param fieldStream The fieldStream to set.
*/
public void setFieldStream(String[] fieldStream)
{
this.fieldStream = fieldStream;
}
public String[] getDateMask() {
return dateMask;
}
public void setDateMask(String[] dateMask) {
this.dateMask = dateMask;
}
public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters)
throws KettleXMLException
{
readData(stepnode, databases);
}
public void allocate(int nrvalues)
{
fieldTable = new String[nrvalues];
fieldStream = new String[nrvalues];
dateMask = new String[nrvalues];
matchColumn = new boolean[nrvalues];
updateColumn = new boolean[nrvalues];
}
public void allocateLocalHosts(int numberOfLocalHosts) {
this.localHosts = new String[numberOfLocalHosts];
}
public Object clone()
{
GPLoadMeta retval = (GPLoadMeta)super.clone();
int nrvalues = fieldTable.length;
retval.allocate(nrvalues);
for (int i=0;i<nrvalues;i++)
{
retval.fieldTable[i] = fieldTable[i];
retval.fieldStream[i] = fieldStream[i];
retval.dateMask[i] = dateMask[i];
retval.matchColumn[i] = matchColumn[i];
retval.updateColumn[i] = updateColumn[i];
}
return retval;
}
private void readData(Node stepnode, List<? extends SharedObjectInterface> databases)
throws KettleXMLException
{
try
{
String con = XMLHandler.getTagValue(stepnode, "connection"); //$NON-NLS-1$
databaseMeta = DatabaseMeta.findDatabase(databases, con);
maxErrors = XMLHandler.getTagValue(stepnode, "errors"); //$NON-NLS-1$
schemaName = XMLHandler.getTagValue(stepnode, "schema"); //$NON-NLS-1$
tableName = XMLHandler.getTagValue(stepnode, "table"); //$NON-NLS-1$
errorTableName = XMLHandler.getTagValue(stepnode, "error_table"); //$NON-NLS-1$
loadMethod = XMLHandler.getTagValue(stepnode, "load_method"); //$NON-NLS-1$
loadAction = XMLHandler.getTagValue(stepnode, "load_action"); //$NON-NLS-1$
gploadPath = XMLHandler.getTagValue(stepnode, "gpload_path"); //$NON-NLS-1$
controlFile = XMLHandler.getTagValue(stepnode, "control_file"); //$NON-NLS-1$
dataFile = XMLHandler.getTagValue(stepnode, "data_file"); //$NON-NLS-1$
delimiter = XMLHandler.getTagValue(stepnode, "delimiter"); //$NON-NLS-1$
logFile = XMLHandler.getTagValue(stepnode, "log_file"); //$NON-NLS-1$
eraseFiles = "Y".equalsIgnoreCase( XMLHandler.getTagValue(stepnode, "erase_files")); //$NON-NLS-1$
encoding = XMLHandler.getTagValue(stepnode, "encoding"); //$NON-NLS-1$
updateCondition = XMLHandler.getTagValue(stepnode, "update_condition"); //$NON-NLS-1$;
Node localHostsNode = XMLHandler.getSubNode(stepnode, "local_hosts");
int nLocalHosts = XMLHandler.countNodes(localHostsNode, "local_host");//$NON-NLS-1$
allocateLocalHosts(nLocalHosts);
for (int i=0; i<nLocalHosts; i++) {
Node localHostNode = XMLHandler.getSubNodeByNr(localHostsNode, "local_host", i); //$NON-NLS-1$
localHosts[i] = XMLHandler.getNodeValue(localHostNode); //$NON-NLS-1$
}
localhostPort = XMLHandler.getTagValue(stepnode, "localhost_port"); //$NON-NLS-1$
int nrvalues = XMLHandler.countNodes(stepnode, "mapping"); //$NON-NLS-1$
allocate(nrvalues);
for (int i=0;i<nrvalues;i++)
{
Node vnode = XMLHandler.getSubNodeByNr(stepnode, "mapping", i); //$NON-NLS-1$
fieldTable[i] = XMLHandler.getTagValue(vnode, "stream_name"); //$NON-NLS-1$
fieldStream[i] = XMLHandler.getTagValue(vnode, "field_name"); //$NON-NLS-1$
if (fieldStream[i]==null) fieldStream[i]=fieldTable[i]; // default: the same name!
String locDateMask = XMLHandler.getTagValue(vnode, "date_mask"); //$NON-NLS-1$
if(locDateMask==null) {
dateMask[i] = "";
}
else
{
if (GPLoadMeta.DATE_MASK_DATE.equals(locDateMask) ||
GPLoadMeta.DATE_MASK_DATETIME.equals(locDateMask) )
{
dateMask[i] = locDateMask;
}
else
{
dateMask[i] = "";
}
}
matchColumn[i] = ("Y".equalsIgnoreCase(XMLHandler.getTagValue(vnode, "match_column"))); //$NON-NLS-1$
updateColumn[i] = ("Y".equalsIgnoreCase(XMLHandler.getTagValue(vnode, "update_column"))); //$NON-NLS-1$
}
}
catch(Exception e)
{
throw new KettleXMLException(BaseMessages.getString(PKG, "GPLoadMeta.Exception.UnableToReadStepInfoFromXML"), e); //$NON-NLS-1$
}
}
public void setDefault()
{
// TODO: Make non empty defaults public static Strings
fieldTable = null;
databaseMeta = null;
maxErrors = GPLoadMeta.MAX_ERRORS_DEFAULT;
schemaName = ""; //$NON-NLS-1$
localhostPort = "";
tableName = BaseMessages.getString(PKG, "GPLoadMeta.DefaultTableName"); //$NON-NLS-1$
errorTableName = ""; //BaseMessages.getString(PKG, "GPLocal.ErrorTable.Prefix")+tableName;
loadMethod = METHOD_AUTO_END;
loadAction = ACTION_INSERT;
gploadPath = "/usr/local/greenplum-db/bin/gpload"; //$NON-NLS-1$
controlFile = "control${Internal.Step.CopyNr}.cfg"; //$NON-NLS-1$
dataFile = "load${Internal.Step.CopyNr}.dat"; //$NON-NLS-1$
logFile = ""; //$NON-NLS-1$
encoding = ""; //$NON-NLS-1$
delimiter = ",";
encloseNumbers = false;
eraseFiles = true;
updateCondition = "";
allocate(0);
allocateLocalHosts(0);
}
public String getXML()
{
StringBuffer retval = new StringBuffer(300);
retval.append(" ").append(XMLHandler.addTagValue("connection", databaseMeta==null?"":databaseMeta.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
retval.append(" ").append(XMLHandler.addTagValue("errors", maxErrors)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("schema", schemaName)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("table", tableName)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("error_table", errorTableName)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("load_method", loadMethod)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("load_action", loadAction)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("gpload_path", gploadPath)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("control_file", controlFile)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("data_file", dataFile)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("delimiter", delimiter)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("log_file", logFile)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("erase_files", eraseFiles)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("encoding", encoding)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("enclose_numbers", (encloseNumbers?"Y":"N"))); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("localhost_port", localhostPort)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("update_condition", updateCondition)); //$NON-NLS-1$ //$NON-NLS-2$
for (int i=0;i<fieldTable.length;i++)
{
retval.append(" <mapping>").append(Const.CR); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.addTagValue("stream_name", fieldTable[i])); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("field_name", fieldStream[i])); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("date_mask", dateMask[i])); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("match_column", (matchColumn[i]?"Y":"N"))); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("update_column", (updateColumn[i]?"Y":"N"))); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" </mapping>").append(Const.CR); //$NON-NLS-1$
}
retval.append(" <local_hosts>").append(Const.CR); //$NON-NLS-1$
for (String localHost: localHosts) {
retval.append(" ").append(XMLHandler.addTagValue("local_host", localHost)); //$NON-NLS-1$ //$NON-NLS-2$
}
retval.append(" </local_hosts>").append(Const.CR); //$NON-NLS-1$
return retval.toString();
}
public void readRep(Repository rep, ObjectId id_step, List<DatabaseMeta> databases, Map<String, Counter> counters)
throws KettleException
{
try
{
databaseMeta = rep.loadDatabaseMetaFromStepAttribute(id_step, "id_connection", databases);
maxErrors = rep.getStepAttributeString(id_step, "errors"); //$NON-NLS-1$
schemaName = rep.getStepAttributeString(id_step, "schema"); //$NON-NLS-1$
tableName = rep.getStepAttributeString(id_step, "table"); //$NON-NLS-1$
errorTableName = rep.getStepAttributeString(id_step, "error_table"); //$NON-NLS-1$
loadMethod = rep.getStepAttributeString(id_step, "load_method"); //$NON-NLS-1$
loadAction = rep.getStepAttributeString(id_step, "load_action"); //$NON-NLS-1$
gploadPath = rep.getStepAttributeString(id_step, "gpload_path"); //$NON-NLS-1$
controlFile = rep.getStepAttributeString(id_step, "control_file"); //$NON-NLS-1$
dataFile = rep.getStepAttributeString(id_step, "data_file"); //$NON-NLS-1$
delimiter = rep.getStepAttributeString(id_step, "delimiter"); //$NON-NLS-1$
logFile = rep.getStepAttributeString(id_step, "log_file"); //$NON-NLS-1$
eraseFiles = rep.getStepAttributeBoolean(id_step, "erase_files"); //$NON-NLS-1$
encoding = rep.getStepAttributeString(id_step, "encoding"); //$NON-NLS-1$
localhostPort = rep.getStepAttributeString(id_step, "localhost_port"); //$NON-NLS-1$
encloseNumbers = (rep.getStepAttributeString(id_step, "enclose_numbers").equalsIgnoreCase("Y")?true:false); //$NON-NLS-1$
updateCondition = rep.getStepAttributeString(id_step, "update_condition"); //$NON-NLS-1$
int numberOfLocalHosts = rep.countNrStepAttributes(id_step, "local_host");
allocateLocalHosts(numberOfLocalHosts);
for (int i=0; i< numberOfLocalHosts; i++) {
localHosts[i] = rep.getStepAttributeString(id_step, i, "local_host"); //$NON-NLS-1$
}
int nrvalues = rep.countNrStepAttributes(id_step, "stream_name"); //$NON-NLS-1$
allocate(nrvalues);
for (int i=0;i<nrvalues;i++)
{
fieldTable[i] = rep.getStepAttributeString(id_step, i, "stream_name"); //$NON-NLS-1$
fieldStream[i] = rep.getStepAttributeString(id_step, i, "field_name"); //$NON-NLS-1$
dateMask[i] = rep.getStepAttributeString(id_step, i, "date_mask"); //$NON-NLS-1$
matchColumn[i] = rep.getStepAttributeBoolean(id_step, i, "match_column"); //$NON-NLS-1$
updateColumn[i] = rep.getStepAttributeBoolean(id_step, i, "update_column"); //$NON-NLS-1$
}
}
catch(Exception e)
{
throw new KettleException(BaseMessages.getString(PKG, "GPLoadMeta.Exception.UnexpectedErrorReadingStepInfoFromRepository"), e); //$NON-NLS-1$
}
}
public void saveRep(Repository rep, ObjectId id_transformation, ObjectId id_step)
throws KettleException
{
try
{
rep.saveDatabaseMetaStepAttribute(id_transformation, id_step, "id_connection", databaseMeta);
rep.saveStepAttribute(id_transformation, id_step, "errors", maxErrors); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "schema", schemaName); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "table", tableName); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "error_table", errorTableName); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "load_method", loadMethod); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "load_action", loadAction); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "gpload_path", gploadPath); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "control_file", controlFile); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "data_file", dataFile); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "delimiter", delimiter); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "log_file", logFile); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "erase_files", eraseFiles); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "encoding", encoding); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "enclose_numbers", (encloseNumbers?"Y":"N"));//$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "localhost_port", localhostPort);//$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "update_condition", updateCondition);//$NON-NLS-1$
for (int i=0;i <localHosts.length; i++) {
rep.saveStepAttribute(id_transformation, id_step, i, "local_host", localHosts[i]); //$NON-NLS-1$
}
for (int i=0;i<fieldTable.length;i++)
{
rep.saveStepAttribute(id_transformation, id_step, i, "stream_name", fieldTable[i]); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, i, "field_name", fieldStream[i]); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, i, "date_mask", dateMask[i]); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, i, "match_column", matchColumn[i]); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, i, "update_column", updateColumn[i]); //$NON-NLS-1$
}
// Also, save the step-database relationship!
if (databaseMeta!=null) rep.insertStepDatabase(id_transformation, id_step, databaseMeta.getObjectId());
}
catch(Exception e)
{
throw new KettleException(BaseMessages.getString(PKG, "GPLoadMeta.Exception.UnableToSaveStepInfoToRepository")+id_step, e); //$NON-NLS-1$
}
}
public void getFields(RowMetaInterface rowMeta, String origin, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space) throws KettleStepException
{
// Default: nothing changes to rowMeta
}
public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String input[], String output[], RowMetaInterface info)
{
CheckResult cr;
String error_message = ""; //$NON-NLS-1$
if (databaseMeta!=null)
{
Database db = new Database(loggingObject, databaseMeta);
db.shareVariablesWith(transMeta);
try
{
db.connect();
if (!Const.isEmpty(tableName))
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.TableNameOK"), stepMeta); //$NON-NLS-1$
remarks.add(cr);
boolean first=true;
boolean error_found=false;
error_message = ""; //$NON-NLS-1$
// Check fields in table
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(
transMeta.environmentSubstitute(schemaName),
transMeta.environmentSubstitute(tableName));
RowMetaInterface r = db.getTableFields(schemaTable);
if (r!=null)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.TableExists"), stepMeta); //$NON-NLS-1$
remarks.add(cr);
// How about the fields to insert/dateMask in the table?
first=true;
error_found=false;
error_message = ""; //$NON-NLS-1$
for (int i=0;i<fieldTable.length;i++)
{
String field = fieldTable[i];
ValueMetaInterface v = r.searchValueMeta(field);
if (v==null)
{
if (first)
{
first=false;
error_message+=BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.MissingFieldsToLoadInTargetTable")+Const.CR; //$NON-NLS-1$
}
error_found=true;
error_message+="\t\t"+field+Const.CR; //$NON-NLS-1$
}
}
if (error_found)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta);
}
else
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.AllFieldsFoundInTargetTable"), stepMeta); //$NON-NLS-1$
}
remarks.add(cr);
}
else
{
error_message=BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.CouldNotReadTableInfo"); //$NON-NLS-1$
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta);
remarks.add(cr);
}
}
// Look up fields in the input stream <prev>
if (prev!=null && prev.size()>0)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.StepReceivingDatas",prev.size()+""), stepMeta); //$NON-NLS-1$ //$NON-NLS-2$
remarks.add(cr);
boolean first=true;
error_message = ""; //$NON-NLS-1$
boolean error_found = false;
for (int i=0;i<fieldStream.length;i++)
{
ValueMetaInterface v = prev.searchValueMeta(fieldStream[i]);
if (v==null)
{
if (first)
{
first=false;
error_message+=BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.MissingFieldsInInput")+Const.CR; //$NON-NLS-1$
}
error_found=true;
error_message+="\t\t"+fieldStream[i]+Const.CR; //$NON-NLS-1$
}
}
if (error_found)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta);
}
else
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.AllFieldsFoundInInput"), stepMeta); //$NON-NLS-1$
}
remarks.add(cr);
}
else
{
error_message=BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.MissingFieldsInInput3")+Const.CR; //$NON-NLS-1$
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta);
remarks.add(cr);
}
}
catch(KettleException e)
{
error_message = BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.DatabaseErrorOccurred")+e.getMessage(); //$NON-NLS-1$
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta);
remarks.add(cr);
}
finally
{
db.disconnect();
}
}
else
{
error_message = BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.InvalidConnection"); //$NON-NLS-1$
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta);
remarks.add(cr);
}
// See if we have input streams leading to this step!
if (input.length>0)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.StepReceivingInfoFromOtherSteps"), stepMeta); //$NON-NLS-1$
remarks.add(cr);
}
else
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString(PKG, "GPLoadMeta.CheckResult.NoInputError"), stepMeta); //$NON-NLS-1$
remarks.add(cr);
}
}
public SQLStatement getSQLStatements(TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev) throws KettleStepException
{
SQLStatement retval = new SQLStatement(stepMeta.getName(), databaseMeta, null); // default: nothing to do!
if (databaseMeta!=null)
{
if (prev!=null && prev.size()>0)
{
// Copy the row
RowMetaInterface tableFields = new RowMeta();
// Now change the field names
for (int i=0;i<fieldTable.length;i++)
{
ValueMetaInterface v = prev.searchValueMeta(fieldStream[i]);
if (v!=null)
{
ValueMetaInterface tableField = v.clone();
tableField.setName(fieldTable[i]);
tableFields.addValueMeta(tableField);
}
else
{
throw new KettleStepException("Unable to find field ["+fieldStream[i]+"] in the input rows");
}
}
if (!Const.isEmpty(tableName))
{
Database db = new Database(loggingObject, databaseMeta);
db.shareVariablesWith(transMeta);
try
{
db.connect();
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(transMeta.environmentSubstitute(schemaName),
transMeta.environmentSubstitute(tableName));
String sql = db.getDDL(schemaTable,
tableFields,
null,
false,
null,
true
);
if (sql.length()==0) retval.setSQL(null); else retval.setSQL(sql);
}
catch(KettleException e)
{
retval.setError(BaseMessages.getString(PKG, "GPLoadMeta.GetSQL.ErrorOccurred")+e.getMessage()); //$NON-NLS-1$
}
}
else
{
retval.setError(BaseMessages.getString(PKG, "GPLoadMeta.GetSQL.NoTableDefinedOnConnection")); //$NON-NLS-1$
}
}
else
{
retval.setError(BaseMessages.getString(PKG, "GPLoadMeta.GetSQL.NotReceivingAnyFields")); //$NON-NLS-1$
}
}
else
{
retval.setError(BaseMessages.getString(PKG, "GPLoadMeta.GetSQL.NoConnectionDefined")); //$NON-NLS-1$
}
return retval;
}
public void analyseImpact(List<DatabaseImpact> impact, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String input[], String output[], RowMetaInterface info) throws KettleStepException
{
if (prev != null)
{
/* DEBUG CHECK THIS */
// Insert dateMask fields : read/write
for (int i = 0; i < fieldTable.length; i++)
{
ValueMetaInterface v = prev.searchValueMeta(fieldStream[i]);
DatabaseImpact ii = new DatabaseImpact(DatabaseImpact.TYPE_IMPACT_READ_WRITE, transMeta.getName(), stepMeta.getName(), databaseMeta.getDatabaseName(),
transMeta.environmentSubstitute(tableName), fieldTable[i], fieldStream[i], v!=null?v.getOrigin():"?", "", "Type = " + v.toStringMeta()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
impact.add(ii);
}
}
}
public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans trans)
{
return new GPLoad(stepMeta, stepDataInterface, cnr, transMeta, trans);
}
public StepDataInterface getStepData()
{
return new GPLoadData();
}
public DatabaseMeta[] getUsedDatabaseConnections()
{
if (databaseMeta!=null)
{
return new DatabaseMeta[] { databaseMeta };
}
else
{
return super.getUsedDatabaseConnections();
}
}
public RowMetaInterface getRequiredFields(VariableSpace space) throws KettleException
{
String realTableName = space.environmentSubstitute(tableName);
String realSchemaName = space.environmentSubstitute(schemaName);
if (databaseMeta!=null)
{
Database db = new Database(loggingObject, databaseMeta);
try
{
db.connect();
if (!Const.isEmpty(realTableName))
{
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(realSchemaName, realTableName);
// Check if this table exists...
if (db.checkTableExists(schemaTable))
{
return db.getTableFields(schemaTable);
}
else
{
throw new KettleException(BaseMessages.getString(PKG, "GPLoadMeta.Exception.TableNotFound"));
}
}
else
{
throw new KettleException(BaseMessages.getString(PKG, "GPLoadMeta.Exception.TableNotSpecified"));
}
}
catch(Exception e)
{
throw new KettleException(BaseMessages.getString(PKG, "GPLoadMeta.Exception.ErrorGettingFields"), e);
}
finally
{
db.disconnect();
}
}
else
{
throw new KettleException(BaseMessages.getString(PKG, "GPLoadMeta.Exception.ConnectionNotDefined"));
}
}
/**
* @return the schemaName
*/
public String getSchemaName()
{
return schemaName;
}
/**
* @param schemaName the schemaName to set
*/
public void setSchemaName(String schemaName)
{
this.schemaName = schemaName;
}
public String getControlFile() {
return controlFile;
}
public void setControlFile(String controlFile) {
this.controlFile = controlFile;
}
public String getDataFile() {
return dataFile;
}
public void setDataFile(String dataFile) {
this.dataFile = dataFile;
}
public String getLogFile() {
return logFile;
}
public void setLogFile(String logFile) {
this.logFile = logFile;
}
public void setLoadAction(String action)
{
this.loadAction = action;
}
public String getLoadAction()
{
return this.loadAction;
}
public void setLoadMethod(String method)
{
this.loadMethod = method;
}
public String getLoadMethod()
{
return this.loadMethod;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
public String getDelimiter() {
return delimiter;
}
public String getEnclosure() {
return "";
}
public boolean isEraseFiles() {
return eraseFiles;
}
public void setEraseFiles(boolean eraseFiles) {
this.eraseFiles = eraseFiles;
}
public String getMaxErrors() {
return maxErrors;
}
public void setMaxErrors(String maxErrors) {
this.maxErrors = maxErrors;
}
public void setEncloseNumbers(boolean encloseNumbers) {
this.encloseNumbers = encloseNumbers;
}
public boolean getEncloseNumbers() {
return this.encloseNumbers;
}
public void setLocalHosts(String[] localHosts) {
this.localHosts = localHosts;
}
public String[] getLocalHosts() {
return localHosts;
}
public void setLocalhostPort(String localhostPort) {
this.localhostPort = localhostPort;
}
public String getLocalhostPort() {
return localhostPort;
}
public void setMatchColumns(boolean[] matchColumn) {
this.matchColumn = matchColumn;
}
public boolean[] getMatchColumn() {
return matchColumn;
}
public void setUpdateColumn(boolean[] updateColumn) {
this.updateColumn = updateColumn;
}
public boolean[] getUpdateColumn() {
return updateColumn;
}
public boolean hasMatchColumn() {
for (boolean matchColumn: this.matchColumn) {
if (matchColumn) {
return true;
}
}
return false;
}
public boolean hasUpdateColumn() {
for (boolean updateColumn: this.updateColumn) {
if (updateColumn) {
return true;
}
}
return false;
}
public void setUpdateCondition(String updateCondition) {
this.updateCondition = updateCondition;
}
public String getUpdateCondition() {
return updateCondition;
}
} | apache-2.0 |
guozhangwang/kafka | streams/src/main/java/org/apache/kafka/streams/StreamsMetrics.java | 7412 | /*
* 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.kafka.streams;
import org.apache.kafka.common.Metric;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.metrics.Sensor;
import java.util.Map;
/**
* The Kafka Streams metrics interface for adding metric sensors and collecting metric values.
*/
public interface StreamsMetrics {
/**
* Get read-only handle on global metrics registry.
*
* @return Map of all metrics.
*/
Map<MetricName, ? extends Metric> metrics();
/**
* Add a latency, rate and total sensor for a specific operation, which will include the following metrics:
* <ol>
* <li>average latency</li>
* <li>max latency</li>
* <li>invocation rate (num.operations / seconds)</li>
* <li>total invocation count</li>
* </ol>
* Whenever a user records this sensor via {@link Sensor#record(double)} etc, it will be counted as one invocation
* of the operation, and hence the rate / count metrics will be updated accordingly; and the recorded latency value
* will be used to update the average / max latency as well.
*
* Note that you can add more metrics to this sensor after you created it, which can then be updated upon
* {@link Sensor#record(double)} calls.
*
* The added sensor and its metrics can be removed with {@link #removeSensor(Sensor) removeSensor()}.
*
* @param scopeName name of the scope, which will be used as part of the metric type, e.g.: "stream-[scope]-metrics".
* @param entityName name of the entity, which will be used as part of the metric tags, e.g.: "[scope]-id" = "[entity]".
* @param operationName name of the operation, which will be used as the name of the metric, e.g.: "[operation]-latency-avg".
* @param recordingLevel the recording level (e.g., INFO or DEBUG) for this sensor.
* @param tags additional tags of the sensor
* @return The added sensor.
* @see #addRateTotalSensor(String, String, String, Sensor.RecordingLevel, String...)
* @see #removeSensor(Sensor)
* @see #addSensor(String, Sensor.RecordingLevel, Sensor...)
*/
Sensor addLatencyRateTotalSensor(final String scopeName,
final String entityName,
final String operationName,
final Sensor.RecordingLevel recordingLevel,
final String... tags);
/**
* Add a rate and a total sensor for a specific operation, which will include the following metrics:
* <ol>
* <li>invocation rate (num.operations / time unit)</li>
* <li>total invocation count</li>
* </ol>
* Whenever a user records this sensor via {@link Sensor#record(double)} etc,
* it will be counted as one invocation of the operation, and hence the rate / count metrics will be updated accordingly.
*
* Note that you can add more metrics to this sensor after you created it, which can then be updated upon
* {@link Sensor#record(double)} calls.
*
* The added sensor and its metrics can be removed with {@link #removeSensor(Sensor) removeSensor()}.
*
* @param scopeName name of the scope, which will be used as part of the metrics type, e.g.: "stream-[scope]-metrics".
* @param entityName name of the entity, which will be used as part of the metric tags, e.g.: "[scope]-id" = "[entity]".
* @param operationName name of the operation, which will be used as the name of the metric, e.g.: "[operation]-total".
* @param recordingLevel the recording level (e.g., INFO or DEBUG) for this sensor.
* @param tags additional tags of the sensor
* @return The added sensor.
* @see #addLatencyRateTotalSensor(String, String, String, Sensor.RecordingLevel, String...)
* @see #removeSensor(Sensor)
* @see #addSensor(String, Sensor.RecordingLevel, Sensor...)
*/
Sensor addRateTotalSensor(final String scopeName,
final String entityName,
final String operationName,
final Sensor.RecordingLevel recordingLevel,
final String... tags);
/**
* Generic method to create a sensor.
* Note that for most cases it is advisable to use
* {@link #addRateTotalSensor(String, String, String, Sensor.RecordingLevel, String...) addRateTotalSensor()}
* or {@link #addLatencyRateTotalSensor(String, String, String, Sensor.RecordingLevel, String...) addLatencyRateTotalSensor()}
* to ensure metric name well-formedness and conformity with the rest of the Kafka Streams code base.
* However, if the above two methods are not sufficient, this method can also be used.
*
* @param name name of the sensor.
* @param recordingLevel the recording level (e.g., INFO or DEBUG) for this sensor
* @return The added sensor.
* @see #addRateTotalSensor(String, String, String, Sensor.RecordingLevel, String...)
* @see #addLatencyRateTotalSensor(String, String, String, Sensor.RecordingLevel, String...)
* @see #removeSensor(Sensor)
*/
Sensor addSensor(final String name,
final Sensor.RecordingLevel recordingLevel);
/**
* Generic method to create a sensor with parent sensors.
* Note that for most cases it is advisable to use
* {@link #addRateTotalSensor(String, String, String, Sensor.RecordingLevel, String...) addRateTotalSensor()}
* or {@link #addLatencyRateTotalSensor(String, String, String, Sensor.RecordingLevel, String...) addLatencyRateTotalSensor()}
* to ensure metric name well-formedness and conformity with the rest of the Kafka Streams code base.
* However, if the above two methods are not sufficient, this method can also be used.
*
* @param name name of the sensor
* @param recordingLevel the recording level (e.g., INFO or DEBUG) for this sensor
* @return The added sensor.
* @see #addRateTotalSensor(String, String, String, Sensor.RecordingLevel, String...)
* @see #addLatencyRateTotalSensor(String, String, String, Sensor.RecordingLevel, String...)
* @see #removeSensor(Sensor)
*/
Sensor addSensor(final String name,
final Sensor.RecordingLevel recordingLevel,
final Sensor... parents);
/**
* Remove a sensor.
* @param sensor sensor to be removed
*/
void removeSensor(final Sensor sensor);
}
| apache-2.0 |
marcus-nl/flowable-engine | modules/flowable-identitylink-service/src/main/java/org/flowable/identitylink/service/IdentityLinkServiceConfiguration.java | 7365 | /* 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.flowable.identitylink.service;
import org.flowable.engine.common.AbstractServiceConfiguration;
import org.flowable.engine.common.impl.history.HistoryLevel;
import org.flowable.identitylink.service.impl.HistoricIdentityLinkServiceImpl;
import org.flowable.identitylink.service.impl.IdentityLinkServiceImpl;
import org.flowable.identitylink.service.impl.persistence.entity.HistoricIdentityLinkEntityManager;
import org.flowable.identitylink.service.impl.persistence.entity.HistoricIdentityLinkEntityManagerImpl;
import org.flowable.identitylink.service.impl.persistence.entity.IdentityLinkEntityManager;
import org.flowable.identitylink.service.impl.persistence.entity.IdentityLinkEntityManagerImpl;
import org.flowable.identitylink.service.impl.persistence.entity.data.HistoricIdentityLinkDataManager;
import org.flowable.identitylink.service.impl.persistence.entity.data.IdentityLinkDataManager;
import org.flowable.identitylink.service.impl.persistence.entity.data.impl.MybatisHistoricIdentityLinkDataManager;
import org.flowable.identitylink.service.impl.persistence.entity.data.impl.MybatisIdentityLinkDataManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author Tijs Rademakers
*/
public class IdentityLinkServiceConfiguration extends AbstractServiceConfiguration {
protected static final Logger LOGGER = LoggerFactory.getLogger(IdentityLinkServiceConfiguration.class);
// SERVICES
// /////////////////////////////////////////////////////////////////
protected IdentityLinkService identityLinkService = new IdentityLinkServiceImpl(this);
protected HistoricIdentityLinkService historicIdentityLinkService = new HistoricIdentityLinkServiceImpl(this);
// DATA MANAGERS ///////////////////////////////////////////////////
protected IdentityLinkDataManager identityLinkDataManager;
protected HistoricIdentityLinkDataManager historicIdentityLinkDataManager;
// ENTITY MANAGERS /////////////////////////////////////////////////
protected IdentityLinkEntityManager identityLinkEntityManager;
protected HistoricIdentityLinkEntityManager historicIdentityLinkEntityManager;
protected HistoryLevel historyLevel;
protected ObjectMapper objectMapper;
// init
// /////////////////////////////////////////////////////////////////////
public void init() {
initDataManagers();
initEntityManagers();
}
@Override
public boolean isHistoryLevelAtLeast(HistoryLevel level) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Current history level: {}, level required: {}", historyLevel, level);
}
// Comparing enums actually compares the location of values declared in the enum
return historyLevel.isAtLeast(level);
}
@Override
public boolean isHistoryEnabled() {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Current history level: {}", historyLevel);
}
return historyLevel != HistoryLevel.NONE;
}
// Data managers
///////////////////////////////////////////////////////////
public void initDataManagers() {
if (identityLinkDataManager == null) {
identityLinkDataManager = new MybatisIdentityLinkDataManager();
}
if (historicIdentityLinkDataManager == null) {
historicIdentityLinkDataManager = new MybatisHistoricIdentityLinkDataManager();
}
}
public void initEntityManagers() {
if (identityLinkEntityManager == null) {
identityLinkEntityManager = new IdentityLinkEntityManagerImpl(this, identityLinkDataManager);
}
if (historicIdentityLinkEntityManager == null) {
historicIdentityLinkEntityManager = new HistoricIdentityLinkEntityManagerImpl(this, historicIdentityLinkDataManager);
}
}
// getters and setters
// //////////////////////////////////////////////////////
public IdentityLinkServiceConfiguration getIdentityLinkServiceConfiguration() {
return this;
}
public IdentityLinkService getIdentityLinkService() {
return identityLinkService;
}
public IdentityLinkServiceConfiguration setIdentityLinkService(IdentityLinkService identityLinkService) {
this.identityLinkService = identityLinkService;
return this;
}
public HistoricIdentityLinkService getHistoricIdentityLinkService() {
return historicIdentityLinkService;
}
public IdentityLinkServiceConfiguration setHistoricIdentityLinkService(HistoricIdentityLinkService historicIdentityLinkService) {
this.historicIdentityLinkService = historicIdentityLinkService;
return this;
}
public IdentityLinkDataManager getIdentityLinkDataManager() {
return identityLinkDataManager;
}
public IdentityLinkServiceConfiguration setIdentityLinkDataManager(IdentityLinkDataManager identityLinkDataManager) {
this.identityLinkDataManager = identityLinkDataManager;
return this;
}
public HistoricIdentityLinkDataManager getHistoricIdentityLinkDataManager() {
return historicIdentityLinkDataManager;
}
public IdentityLinkServiceConfiguration setHistoricIdentityLinkDataManager(HistoricIdentityLinkDataManager historicIdentityLinkDataManager) {
this.historicIdentityLinkDataManager = historicIdentityLinkDataManager;
return this;
}
public IdentityLinkEntityManager getIdentityLinkEntityManager() {
return identityLinkEntityManager;
}
public IdentityLinkServiceConfiguration setIdentityLinkEntityManager(IdentityLinkEntityManager identityLinkEntityManager) {
this.identityLinkEntityManager = identityLinkEntityManager;
return this;
}
public HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return historicIdentityLinkEntityManager;
}
public IdentityLinkServiceConfiguration setHistoricIdentityLinkEntityManager(HistoricIdentityLinkEntityManager historicIdentityLinkEntityManager) {
this.historicIdentityLinkEntityManager = historicIdentityLinkEntityManager;
return this;
}
@Override
public HistoryLevel getHistoryLevel() {
return historyLevel;
}
@Override
public IdentityLinkServiceConfiguration setHistoryLevel(HistoryLevel historyLevel) {
this.historyLevel = historyLevel;
return this;
}
@Override
public ObjectMapper getObjectMapper() {
return objectMapper;
}
@Override
public IdentityLinkServiceConfiguration setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
}
}
| apache-2.0 |
os890/wink_patches | wink-itests/wink-itest/wink-itest-providers/src/main/java/org/apache/wink/itest/subresource/Comment.java | 1537 | /*
* 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.wink.itest.subresource;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "comment")
public class Comment {
private Integer id;
private String message;
private String author;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@XmlElement(nillable = false)
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
| apache-2.0 |
tombujok/hazelcast | hazelcast-spring/src/test/java/com/hazelcast/spring/context/SomeEntryProcessor.java | 1516 | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.spring.context;
import com.hazelcast.map.AbstractEntryProcessor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.Map;
@SpringAware
public class SomeEntryProcessor extends AbstractEntryProcessor implements ApplicationContextAware {
private transient ApplicationContext context;
@Autowired
private transient SomeBean someBean;
@Override
public Object process(Map.Entry entry) {
if (someBean == null) {
return ">null";
}
return "notNull";
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
}
| apache-2.0 |
Bananeweizen/cgeo | main/src/cgeo/geocaching/storage/LocalStorage.java | 15638 | package cgeo.geocaching.storage;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;
import cgeo.geocaching.activity.Progress;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.settings.SettingsActivity;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.AndroidRxUtils;
import cgeo.geocaching.utils.EnvironmentUtils;
import cgeo.geocaching.utils.FileUtils;
import cgeo.geocaching.utils.Log;
import android.app.ProgressDialog;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.os.EnvironmentCompat;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.regex.Pattern;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.StringUtils;
/**
* Handle local storage issues on phone and SD card.
*/
public final class LocalStorage {
public static final Pattern GEOCACHE_FILE_PATTERN = Pattern.compile("^(GC|TB|TC|CC|LC|EC|GK|MV|TR|VI|MS|EV|CT|GE|GA|WM|O)[A-Z0-9]{2,7}$");
private static final String FILE_SYSTEM_TABLE_PATH = "/system/etc/vold.fstab";
private static final String CGEO_DIRNAME = "cgeo";
private static final String DATABASES_DIRNAME = "databases";
private static final String BACKUP_DIR_NAME = "backup";
private static final String GPX_DIR_NAME = "gpx";
private static final String FIELD_NOTES_DIR_NAME = "field-notes";
private static final String LEGACY_CGEO_DIR_NAME = ".cgeo";
private static final String GEOCACHE_PHOTOS_DIR_NAME = "GeocachePhotos";
private static final String GEOCACHE_DATA_DIR_NAME = "GeocacheData";
private static final long LOW_DISKSPACE_THRESHOLD = 1024 * 1024 * 100; // 100 MB in bytes
private static File internalCgeoDirectory;
private static File externalPrivateCgeoDirectory;
private static File externalPublicCgeoDirectory;
private LocalStorage() {
// utility class
}
/**
* Usually <pre>/data/data/cgeo.geocaching</pre>
*/
@NonNull
public static File getInternalCgeoDirectory() {
if (internalCgeoDirectory == null) {
// A race condition will do no harm as the operation is idempotent. No need to synchronize.
internalCgeoDirectory = CgeoApplication.getInstance().getApplicationContext().getFilesDir().getParentFile();
}
return internalCgeoDirectory;
}
/**
* Returns all available external private cgeo directories, e.g.:
* <pre>
* /sdcard/Android/data/cgeo.geocaching/files
* /storage/emulated/0/Android/data/cgeo.geocaching/files
* /storage/extSdCard/Android/data/cgeo.geocaching/files
* /mnt/sdcard/Android/data/cgeo.geocaching/files
* /storage/sdcard1/Android/data/cgeo.geocaching/files
* </pre>
*/
@NonNull
public static List<File> getAvailableExternalPrivateCgeoDirectories() {
final List<File> availableExtDirs = new ArrayList<>();
final File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(CgeoApplication.getInstance(), null);
for (final File dir : externalFilesDirs) {
if (dir != null && EnvironmentCompat.getStorageState(dir).equals(Environment.MEDIA_MOUNTED)) {
availableExtDirs.add(dir);
Log.i("Added '" + dir + "' as available external dir");
} else {
Log.w("'" + dir + "' is NOT available as external dir");
}
}
return availableExtDirs;
}
/**
* Usually one of {@link LocalStorage#getAvailableExternalPrivateCgeoDirectories()}.
* Fallback to {@link LocalStorage#getFirstExternalPrivateCgeoDirectory()}
*/
@NonNull
public static File getExternalPrivateCgeoDirectory() {
if (externalPrivateCgeoDirectory == null) {
// find the one selected in preferences
final String prefDirectory = Settings.getExternalPrivateCgeoDirectory();
for (final File dir : getAvailableExternalPrivateCgeoDirectories()) {
if (dir.getAbsolutePath().equals(prefDirectory)) {
externalPrivateCgeoDirectory = dir;
break;
}
}
// fallback to default external files dir
if (externalPrivateCgeoDirectory == null) {
Log.w("Chosen extCgeoDir " + prefDirectory + " is not an available external dir, falling back to default extCgeoDir");
externalPrivateCgeoDirectory = getFirstExternalPrivateCgeoDirectory();
}
if (prefDirectory == null) {
Settings.setExternalPrivateCgeoDirectory(externalPrivateCgeoDirectory.getAbsolutePath());
}
}
return externalPrivateCgeoDirectory;
}
/**
* Uses {@link android.content.Context#getExternalFilesDir(String)} with "null".
* This is usually the emulated external storage.
* It falls back to {@link LocalStorage#getInternalCgeoDirectory()}.
*/
@NonNull
public static File getFirstExternalPrivateCgeoDirectory() {
final File externalFilesDir = CgeoApplication.getInstance().getExternalFilesDir(null);
// fallback to internal dir
if (externalFilesDir == null) {
Log.w("No extCgeoDir is available, falling back to internal storage");
return getInternalCgeoDirectory();
}
return externalFilesDir;
}
@NonNull
public static File getExternalDbDirectory() {
return new File(getFirstExternalPrivateCgeoDirectory(), DATABASES_DIRNAME);
}
@NonNull
public static File getInternalDbDirectory() {
return new File(getInternalCgeoDirectory(), DATABASES_DIRNAME);
}
/**
* Get the primary geocache data directory for a geocode. A null or empty geocode will be replaced by a default
* value.
*
* @param geocode
* the geocode
* @return the geocache data directory
*/
@NonNull
public static File getGeocacheDataDirectory(@NonNull final String geocode) {
return new File(getGeocacheDataDirectory(), geocode);
}
/**
* Get the primary file corresponding to a geocode and a file name or an url. If it is an url, an appropriate
* filename will be built by hashing it. The directory structure will be created if needed.
* A null or empty geocode will be replaced by a default value.
*
* @param geocode
* the geocode
* @param fileNameOrUrl
* the file name or url
* @param isUrl
* true if an url was given, false if a file name was given
* @return the file
*/
@NonNull
public static File getGeocacheDataFile(@NonNull final String geocode, @NonNull final String fileNameOrUrl, final boolean isUrl, final boolean createDirs) {
return FileUtils.buildFile(getGeocacheDataDirectory(geocode), fileNameOrUrl, isUrl, createDirs);
}
/**
* Check if an external media (SD card) is available for use.
*
* @return true if the external media is properly mounted
*/
public static boolean isExternalStorageAvailable() {
return EnvironmentUtils.isExternalStorageAvailable();
}
/**
* Deletes all files from geocode cache directory with the given prefix.
*
* @param geocode
* The geocode identifying the cache directory
* @param prefix
* The filename prefix
*/
public static void deleteCacheFilesWithPrefix(@NonNull final String geocode, @NonNull final String prefix) {
FileUtils.deleteFilesWithPrefix(getGeocacheDataDirectory(geocode), prefix);
}
/**
* Get all storages available on the device.
* Will include paths like /mnt/sdcard /mnt/usbdisk /mnt/ext_card /mnt/sdcard/ext_card
*/
@NonNull
public static List<File> getStorages() {
final String extStorage = Environment.getExternalStorageDirectory().getAbsolutePath();
final List<File> storages = new ArrayList<>();
storages.add(new File(extStorage));
final File file = new File(FILE_SYSTEM_TABLE_PATH);
if (file.canRead()) {
try {
for (final String str : org.apache.commons.io.FileUtils.readLines(file, CharEncoding.UTF_8)) {
if (str.startsWith("dev_mount")) {
final String[] tokens = StringUtils.split(str);
if (tokens.length >= 3) {
final String path = tokens[2]; // mountpoint
if (!extStorage.equals(path)) {
final File directory = new File(path);
if (directory.exists() && directory.isDirectory()) {
storages.add(directory);
}
}
}
}
}
} catch (final IOException e) {
Log.e("Could not get additional mount points for user content. " +
"Proceeding with external storage only (" + extStorage + ")", e);
}
}
return storages;
}
/**
* Returns the external public cgeo directory, something like <pre>/sdcard/cgeo</pre>.
* It falls back to the internal cgeo directory if the external is not available.
*/
@NonNull
public static File getExternalPublicCgeoDirectory() {
if (externalPublicCgeoDirectory == null) {
externalPublicCgeoDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), CGEO_DIRNAME);
FileUtils.mkdirs(externalPublicCgeoDirectory);
if (!externalPublicCgeoDirectory.exists() || !externalPublicCgeoDirectory.canWrite()) {
Log.w("External public cgeo directory '" + externalPublicCgeoDirectory + "' not available");
externalPublicCgeoDirectory = getInternalCgeoDirectory();
Log.i("Fallback to internal storage: " + externalPublicCgeoDirectory);
}
}
return externalPublicCgeoDirectory;
}
@NonNull
public static File getFieldNotesDirectory() {
return new File(getExternalPublicCgeoDirectory(), FIELD_NOTES_DIR_NAME);
}
@NonNull
public static File getLegacyFieldNotesDirectory() {
return new File(Environment.getExternalStorageDirectory(), FIELD_NOTES_DIR_NAME);
}
@NonNull
public static File getDefaultGpxDirectory() {
return new File(getExternalPublicCgeoDirectory(), GPX_DIR_NAME);
}
@NonNull
public static File getGpxExportDirectory() {
final File gpxExportDir = new File(Settings.getGpxExportDir());
FileUtils.mkdirs(gpxExportDir);
if (!gpxExportDir.isDirectory() || !gpxExportDir.canWrite()) {
return getDefaultGpxDirectory();
}
return gpxExportDir;
}
@NonNull
public static File getGpxImportDirectory() {
return new File(Settings.getGpxImportDir());
}
@NonNull
public static File getLegacyGpxDirectory() {
return new File(Environment.getExternalStorageDirectory(), GPX_DIR_NAME);
}
@NonNull
public static File getLegacyExternalCgeoDirectory() {
return new File(Environment.getExternalStorageDirectory(), LEGACY_CGEO_DIR_NAME);
}
@NonNull
public static File getBackupDirectory() {
return new File(getExternalPublicCgeoDirectory(), BACKUP_DIR_NAME);
}
@NonNull
public static File getGeocacheDataDirectory() {
return new File(getExternalPrivateCgeoDirectory(), GEOCACHE_DATA_DIR_NAME);
}
@NonNull
public static File getLocalSpoilersDirectory() {
return new File(getExternalPublicCgeoDirectory(), GEOCACHE_PHOTOS_DIR_NAME);
}
@NonNull
public static File getLegacyLocalSpoilersDirectory() {
return new File(Environment.getExternalStorageDirectory(), GEOCACHE_PHOTOS_DIR_NAME);
}
@NonNull
public static List<File> getMapDirectories() {
final List<File> folders = new ArrayList<>();
for (final File dir : getStorages()) {
folders.add(new File(dir, "mfmaps"));
folders.add(new File(new File(dir, "Locus"), "mapsVector"));
folders.add(new File(dir, CGEO_DIRNAME));
}
return folders;
}
@NonNull
public static File getLogPictureDirectory() {
return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), CGEO_DIRNAME);
}
public static void changeExternalPrivateCgeoDir(final SettingsActivity fromActivity, final String newExtDir) {
final Progress progress = new Progress();
progress.show(fromActivity, fromActivity.getString(R.string.init_datadirmove_datadirmove), fromActivity.getString(R.string.init_datadirmove_running), ProgressDialog.STYLE_HORIZONTAL, null);
AndroidRxUtils.bindActivity(fromActivity, Observable.defer(new Callable<Observable<Boolean>>() {
@Override
public Observable<Boolean> call() {
final File newDataDir = new File(newExtDir, GEOCACHE_DATA_DIR_NAME);
final File currentDataDir = new File(getExternalPrivateCgeoDirectory(), GEOCACHE_DATA_DIR_NAME);
Log.i("Moving geocache data to " + newDataDir.getAbsolutePath());
final File[] files = currentDataDir.listFiles();
boolean success = true;
if (ArrayUtils.isNotEmpty(files)) {
progress.setMaxProgressAndReset(files.length);
progress.setProgress(0);
for (final File geocacheDataDir : files) {
success &= FileUtils.moveTo(geocacheDataDir, newDataDir);
progress.incrementProgressBy(1);
}
}
Settings.setExternalPrivateCgeoDirectory(newExtDir);
Log.i("Ext private c:geo dir was moved to " + newExtDir);
externalPrivateCgeoDirectory = new File(newExtDir);
return Observable.just(success);
}
}).subscribeOn(Schedulers.io())).subscribe(new Consumer<Boolean>() {
@Override
public void accept(final Boolean success) {
progress.dismiss();
final String message = success ? fromActivity.getString(R.string.init_datadirmove_success) : fromActivity.getString(R.string.init_datadirmove_failed);
Dialogs.message(fromActivity, R.string.init_datadirmove_datadirmove, message);
}
});
}
public static boolean isRunningLowOnDiskSpace() {
return FileUtils.getFreeDiskSpace(getExternalPrivateCgeoDirectory()) < LOW_DISKSPACE_THRESHOLD;
}
public static void initGeocacheDataDir() {
final File nomedia = new File(getGeocacheDataDirectory(), ".nomedia");
if (!nomedia.exists()) {
try {
FileUtils.mkdirs(nomedia.getParentFile());
nomedia.createNewFile();
} catch (final IOException e) {
Log.w("Couldn't create the .nomedia file in " + getGeocacheDataDirectory(), e);
}
}
}
}
| apache-2.0 |
okalmanRH/jboss-activemq-artemis | tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/BasicOpenWireTest.java | 8880 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.openwire;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQXAConnectionFactory;
import org.apache.activemq.artemis.api.core.ActiveMQNonExistentQueueException;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.command.ActiveMQDestination;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
public class BasicOpenWireTest extends OpenWireTestBase {
@Rule
public TestName name = new TestName();
protected static final String urlString = "tcp://" + OWHOST + ":" + OWPORT + "?wireFormat.cacheEnabled=true";
protected ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(urlString);
protected ActiveMQXAConnectionFactory xaFactory = new ActiveMQXAConnectionFactory(urlString);
protected ActiveMQConnection connection;
protected String topicName = "amqTestTopic1";
protected String queueName = "amqTestQueue1";
protected String topicName2 = "amqTestTopic2";
protected String queueName2 = "amqTestQueue2";
protected String durableQueueName = "durableQueueName";
protected String messageTextPrefix = "";
protected boolean topic = true;
protected Map<String, SimpleString> testQueues = new HashMap<>();
@Override
@Before
public void setUp() throws Exception {
super.setUp();
SimpleString coreQueue = new SimpleString("jms.queue." + queueName);
this.server.createQueue(coreQueue, coreQueue, null, false, false);
testQueues.put(queueName, coreQueue);
SimpleString coreQueue2 = new SimpleString("jms.queue." + queueName2);
this.server.createQueue(coreQueue2, coreQueue2, null, false, false);
testQueues.put(queueName2, coreQueue2);
SimpleString durableQueue = new SimpleString("jms.queue." + durableQueueName);
this.server.createQueue(durableQueue, durableQueue, null, true, false);
testQueues.put(durableQueueName, durableQueue);
if (!enableSecurity) {
connection = (ActiveMQConnection) factory.createConnection();
}
}
@Override
@After
public void tearDown() throws Exception {
System.out.println("tear down! " + connection);
try {
if (connection != null) {
System.out.println("closing connection");
connection.close();
System.out.println("connection closed.");
}
Iterator<SimpleString> iterQueues = testQueues.values().iterator();
while (iterQueues.hasNext()) {
SimpleString coreQ = iterQueues.next();
try {
this.server.destroyQueue(coreQ, null, false, true);
} catch (ActiveMQNonExistentQueueException idontcare) {
// i don't care if this failed. it means it didn't find the queue
} catch (Throwable e) {
// just print, what else can we do?
e.printStackTrace();
}
System.out.println("Destroyed queue: " + coreQ);
}
testQueues.clear();
} catch (Throwable e) {
System.out.println("Exception !! " + e);
e.printStackTrace();
} finally {
super.tearDown();
System.out.println("Super done.");
}
}
public ActiveMQDestination createDestination(Session session, byte type, String name) throws Exception {
if (name == null) {
return createDestination(session, type);
}
switch (type) {
case ActiveMQDestination.QUEUE_TYPE:
makeSureCoreQueueExist(name);
return (ActiveMQDestination) session.createQueue(name);
case ActiveMQDestination.TOPIC_TYPE:
return (ActiveMQDestination) session.createTopic(name);
case ActiveMQDestination.TEMP_QUEUE_TYPE:
return (ActiveMQDestination) session.createTemporaryQueue();
case ActiveMQDestination.TEMP_TOPIC_TYPE:
return (ActiveMQDestination) session.createTemporaryTopic();
default:
throw new IllegalArgumentException("type: " + type);
}
}
public void makeSureCoreQueueExist(String qname) throws Exception {
SimpleString coreQ = testQueues.get(qname);
if (coreQ == null) {
coreQ = new SimpleString("jms.queue." + qname);
this.server.createQueue(coreQ, coreQ, null, false, false);
testQueues.put(qname, coreQ);
}
}
public ActiveMQDestination createDestination(Session session, byte type) throws JMSException {
switch (type) {
case ActiveMQDestination.QUEUE_TYPE:
return (ActiveMQDestination) session.createQueue(queueName);
case ActiveMQDestination.TOPIC_TYPE:
return (ActiveMQDestination) session.createTopic(topicName);
case ActiveMQDestination.TEMP_QUEUE_TYPE:
return (ActiveMQDestination) session.createTemporaryQueue();
case ActiveMQDestination.TEMP_TOPIC_TYPE:
return (ActiveMQDestination) session.createTemporaryTopic();
default:
throw new IllegalArgumentException("type: " + type);
}
}
protected ActiveMQDestination createDestination2(Session session, byte type) throws JMSException {
switch (type) {
case ActiveMQDestination.QUEUE_TYPE:
return (ActiveMQDestination) session.createQueue(queueName2);
case ActiveMQDestination.TOPIC_TYPE:
return (ActiveMQDestination) session.createTopic(topicName2);
case ActiveMQDestination.TEMP_QUEUE_TYPE:
return (ActiveMQDestination) session.createTemporaryQueue();
case ActiveMQDestination.TEMP_TOPIC_TYPE:
return (ActiveMQDestination) session.createTemporaryTopic();
default:
throw new IllegalArgumentException("type: " + type);
}
}
protected void sendMessages(Session session, Destination destination, int count) throws JMSException {
MessageProducer producer = session.createProducer(destination);
sendMessages(session, producer, count);
producer.close();
}
protected void sendMessages(Session session, MessageProducer producer, int count) throws JMSException {
for (int i = 0; i < count; i++) {
producer.send(session.createTextMessage(messageTextPrefix + i));
}
}
protected void sendMessages(Connection connection, Destination destination, int count) throws JMSException {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
sendMessages(session, destination, count);
session.close();
}
/**
* @param messsage
* @param firstSet
* @param secondSet
*/
protected void assertTextMessagesEqual(String messsage,
Message[] firstSet,
Message[] secondSet) throws JMSException {
assertEquals("Message count does not match: " + messsage, firstSet.length, secondSet.length);
for (int i = 0; i < secondSet.length; i++) {
TextMessage m1 = (TextMessage) firstSet[i];
TextMessage m2 = (TextMessage) secondSet[i];
assertFalse("Message " + (i + 1) + " did not match : " + messsage + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null);
assertEquals("Message " + (i + 1) + " did not match: " + messsage + ": expected {" + m1 + "}, but was {" + m2 + "}", m1.getText(), m2.getText());
}
}
protected Connection createConnection() throws JMSException {
return factory.createConnection();
}
protected void safeClose(Session s) {
try {
s.close();
} catch (Throwable e) {
}
}
}
| apache-2.0 |
voipp/ignite | modules/ml/src/test/java/org/apache/ignite/ml/math/impls/vector/VectorImplementationsFixtures.java | 14939 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.ml.math.impls.vector;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.ignite.ml.math.Matrix;
import org.apache.ignite.ml.math.StorageConstants;
import org.apache.ignite.ml.math.Vector;
import org.apache.ignite.ml.math.impls.matrix.DenseLocalOnHeapMatrix;
import org.jetbrains.annotations.NotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/** */
class VectorImplementationsFixtures {
/** */
private static final List<Supplier<Iterable<Vector>>> suppliers = Arrays.asList(
(Supplier<Iterable<Vector>>)DenseLocalOnHeapVectorFixture::new,
(Supplier<Iterable<Vector>>)DenseLocalOffHeapVectorFixture::new,
(Supplier<Iterable<Vector>>)SparseLocalVectorFixture::new,
(Supplier<Iterable<Vector>>)DelegatingVectorFixture::new,
(Supplier<Iterable<Vector>>)MatrixVectorViewFixture::new,
(Supplier<Iterable<Vector>>)SparseLocalOffHeapVectorFixture::new
);
/** */
void consumeSampleVectors(Consumer<Integer> paramsConsumer, BiConsumer<Vector, String> consumer) {
for (Supplier<Iterable<Vector>> fixtureSupplier : VectorImplementationsFixtures.suppliers) {
final Iterable<Vector> fixture = fixtureSupplier.get();
for (Vector v : fixture) {
if (paramsConsumer != null)
paramsConsumer.accept(v.size());
consumer.accept(v, fixture.toString());
}
}
}
/** */
void selfTest() {
new VectorSizesExtraIterator<>("VectorSizesExtraIterator test",
(size, shallowCp) -> new DenseLocalOnHeapVector(new double[size], shallowCp),
null, "shallow copy", new Boolean[] {false, true, null}).selfTest();
new VectorSizesIterator("VectorSizesIterator test", DenseLocalOffHeapVector::new, null).selfTest();
}
/** */
private static class DenseLocalOnHeapVectorFixture extends VectorSizesExtraFixture<Boolean> {
/** */
DenseLocalOnHeapVectorFixture() {
super("DenseLocalOnHeapVector",
(size, shallowCp) -> new DenseLocalOnHeapVector(new double[size], shallowCp),
"shallow copy", new Boolean[] {false, true, null});
}
}
/** */
private static class DenseLocalOffHeapVectorFixture extends VectorSizesFixture {
/** */
DenseLocalOffHeapVectorFixture() {
super("DenseLocalOffHeapVector", DenseLocalOffHeapVector::new);
}
}
/** */
private static class SparseLocalVectorFixture extends VectorSizesExtraFixture<Integer> {
/** */
SparseLocalVectorFixture() {
super("SparseLocalVector", SparseLocalVector::new, "access mode",
new Integer[] {StorageConstants.SEQUENTIAL_ACCESS_MODE, StorageConstants.RANDOM_ACCESS_MODE, null});
}
}
/** */
private static class MatrixVectorViewFixture extends VectorSizesExtraFixture<Integer> {
/** */
MatrixVectorViewFixture() {
super("MatrixVectorView",
MatrixVectorViewFixture::newView,
"stride kind", new Integer[] {0, 1, 2, null});
}
/** */
private static Vector newView(int size, int strideKind) {
final Matrix parent = new DenseLocalOnHeapMatrix(size, size);
return new MatrixVectorView(parent, 0, 0, strideKind != 1 ? 1 : 0, strideKind != 0 ? 1 : 0);
}
}
/** */
private static class VectorSizesExtraFixture<T> implements Iterable<Vector> {
/** */
private final Supplier<VectorSizesExtraIterator<T>> iter;
/** */
private final AtomicReference<String> ctxDescrHolder = new AtomicReference<>("Iterator not started.");
/** */
VectorSizesExtraFixture(String vectorKind, BiFunction<Integer, T, Vector> ctor, String extraParamName,
T[] extras) {
iter = () -> new VectorSizesExtraIterator<>(vectorKind, ctor, ctxDescrHolder::set, extraParamName, extras);
}
/** {@inheritDoc} */
@NotNull
@Override public Iterator<Vector> iterator() {
return iter.get();
}
/** {@inheritDoc} */
@Override public String toString() {
// IMPL NOTE index within bounds is expected to be guaranteed by proper code in this class
return ctxDescrHolder.get();
}
}
/** */
private static abstract class VectorSizesFixture implements Iterable<Vector> {
/** */
private final Supplier<VectorSizesIterator> iter;
/** */
private final AtomicReference<String> ctxDescrHolder = new AtomicReference<>("Iterator not started.");
/** */
VectorSizesFixture(String vectorKind, Function<Integer, Vector> ctor) {
iter = () -> new VectorSizesIterator(vectorKind, ctor, ctxDescrHolder::set);
}
/** {@inheritDoc} */
@NotNull
@Override public Iterator<Vector> iterator() {
return iter.get();
}
/** {@inheritDoc} */
@Override public String toString() {
// IMPL NOTE index within bounds is expected to be guaranteed by proper code in this class
return ctxDescrHolder.get();
}
}
/** */
private static class VectorSizesExtraIterator<T> extends VectorSizesIterator {
/** */
private final T[] extras;
/** */
private int extraIdx = 0;
/** */
private final BiFunction<Integer, T, Vector> ctor;
/** */
private final String extraParamName;
/**
* @param vectorKind Descriptive name to use for context logging.
* @param ctor Constructor for objects to iterate over.
* @param ctxDescrConsumer Context logging consumer.
* @param extraParamName Name of extra parameter to iterate over.
* @param extras Array of extra parameter values to iterate over.
*/
VectorSizesExtraIterator(String vectorKind, BiFunction<Integer, T, Vector> ctor,
Consumer<String> ctxDescrConsumer, String extraParamName, T[] extras) {
super(vectorKind, null, ctxDescrConsumer);
this.ctor = ctor;
this.extraParamName = extraParamName;
this.extras = extras;
}
/** {@inheritDoc} */
@Override public boolean hasNext() {
return super.hasNext() && hasNextExtra(extraIdx);
}
/** {@inheritDoc} */
@Override void nextIdx() {
assert extras[extraIdx] != null
: "Index(es) out of bound at " + VectorSizesExtraIterator.this;
if (hasNextExtra(extraIdx + 1)) {
extraIdx++;
return;
}
extraIdx = 0;
super.nextIdx();
}
/** {@inheritDoc} */
@Override public String toString() {
// IMPL NOTE index within bounds is expected to be guaranteed by proper code in this class
return "{" + super.toString() +
", " + extraParamName + "=" + extras[extraIdx] +
'}';
}
/** {@inheritDoc} */
@Override BiFunction<Integer, Integer, Vector> ctor() {
return (size, delta) -> ctor.apply(size + delta, extras[extraIdx]);
}
/** */
void selfTest() {
final Set<Integer> extraIdxs = new HashSet<>();
int cnt = 0;
while (hasNext()) {
assertNotNull("Expect not null vector at " + this, next());
if (extras[extraIdx] != null)
extraIdxs.add(extraIdx);
cnt++;
}
assertEquals("Extra param tested", extraIdxs.size(), extras.length - 1);
assertEquals("Combinations tested mismatch.",
7 * 3 * (extras.length - 1), cnt);
}
/** */
private boolean hasNextExtra(int idx) {
return extras[idx] != null;
}
}
/** */
private static class VectorSizesIterator extends TwoParamsIterator<Integer, Integer> {
/** */
private final Function<Integer, Vector> ctor;
/** */
VectorSizesIterator(String vectorKind, Function<Integer, Vector> ctor, Consumer<String> ctxDescrConsumer) {
super(vectorKind, null, ctxDescrConsumer,
"size", new Integer[] {2, 4, 8, 16, 32, 64, 128, null},
"size delta", new Integer[] {-1, 0, 1, null});
this.ctor = ctor;
}
/** {@inheritDoc} */
@Override BiFunction<Integer, Integer, Vector> ctor() {
return (size, delta) -> ctor.apply(size + delta);
}
}
/** */
private static class TwoParamsIterator<T, U> implements Iterator<Vector> {
/** */
private final T params1[];
/** */
private final U params2[];
/** */
private final String vectorKind;
/** */
private final String param1Name;
/** */
private final String param2Name;
/** */
private final BiFunction<T, U, Vector> ctor;
/** */
private final Consumer<String> ctxDescrConsumer;
/** */
private int param1Idx = 0;
/** */
private int param2Idx = 0;
/** */
TwoParamsIterator(String vectorKind, BiFunction<T, U, Vector> ctor,
Consumer<String> ctxDescrConsumer, String param1Name, T[] params1, String param2Name, U[] params2) {
this.param1Name = param1Name;
this.params1 = params1;
this.param2Name = param2Name;
this.params2 = params2;
this.vectorKind = vectorKind;
this.ctor = ctor;
this.ctxDescrConsumer = ctxDescrConsumer;
}
/** {@inheritDoc} */
@Override public boolean hasNext() {
return hasNextParam1(param1Idx) && hasNextParam2(param2Idx);
}
/** {@inheritDoc} */
@Override public Vector next() {
if (!hasNext())
throw new NoSuchElementException(TwoParamsIterator.this.toString());
if (ctxDescrConsumer != null)
ctxDescrConsumer.accept(toString());
Vector res = ctor().apply(params1[param1Idx], params2[param2Idx]);
nextIdx();
return res;
}
/** */
void selfTest() {
final Set<Integer> sizeIdxs = new HashSet<>(), deltaIdxs = new HashSet<>();
int cnt = 0;
while (hasNext()) {
assertNotNull("Expect not null vector at " + this, next());
if (params1[param1Idx] != null)
sizeIdxs.add(param1Idx);
if (params2[param2Idx] != null)
deltaIdxs.add(param2Idx);
cnt++;
}
assertEquals("Sizes tested mismatch.", sizeIdxs.size(), params1.length - 1);
assertEquals("Deltas tested", deltaIdxs.size(), params2.length - 1);
assertEquals("Combinations tested mismatch.",
(params1.length - 1) * (params2.length - 1), cnt);
}
/** IMPL NOTE override in subclasses if needed */
void nextIdx() {
assert params1[param1Idx] != null && params2[param2Idx] != null
: "Index(es) out of bound at " + TwoParamsIterator.this;
if (hasNextParam2(param2Idx + 1)) {
param2Idx++;
return;
}
param2Idx = 0;
param1Idx++;
}
/** {@inheritDoc} */
@Override public String toString() {
// IMPL NOTE index within bounds is expected to be guaranteed by proper code in this class
return vectorKind + "{" + param1Name + "=" + params1[param1Idx] +
", " + param2Name + "=" + params2[param2Idx] +
'}';
}
/** IMPL NOTE override in subclasses if needed */
BiFunction<T, U, Vector> ctor() {
return ctor;
}
/** */
private boolean hasNextParam1(int idx) {
return params1[idx] != null;
}
/** */
private boolean hasNextParam2(int idx) {
return params2[idx] != null;
}
}
/** Delegating vector with dense local onheap vector */
private static class DelegatingVectorFixture implements Iterable<Vector> {
/** */
private final Supplier<VectorSizesExtraIterator<Boolean>> iter;
/** */
private final AtomicReference<String> ctxDescrHolder = new AtomicReference<>("Iterator not started.");
/** */
DelegatingVectorFixture() {
iter = () -> new VectorSizesExtraIterator<>("DelegatingVector with DenseLocalOnHeapVector",
(size, shallowCp) -> new DelegatingVector(new DenseLocalOnHeapVector(new double[size], shallowCp)),
ctxDescrHolder::set, "shallow copy", new Boolean[] {false, true, null});
}
/** {@inheritDoc} */
@NotNull
@Override public Iterator<Vector> iterator() {
return iter.get();
}
/** {@inheritDoc} */
@Override public String toString() {
// IMPL NOTE index within bounds is expected to be guaranteed by proper code in this class
return ctxDescrHolder.get();
}
}
/** */
private static class SparseLocalOffHeapVectorFixture extends VectorSizesFixture {
/** */
SparseLocalOffHeapVectorFixture() {
super("SparseLocalOffHeapVector", SparseLocalOffHeapVector::new);
}
}
}
| apache-2.0 |
goodwinnk/intellij-community | plugins/IntentionPowerPak/src/com/siyeh/ipp/trivialif/MergeElseIfIntention.java | 3309 | /*
* Copyright 2003-2015 Dave Griffith, Bas Leijdekkers
*
* 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.siyeh.ipp.trivialif;
import com.intellij.psi.*;
import com.siyeh.ig.PsiReplacementUtil;
import com.siyeh.ipp.base.Intention;
import com.siyeh.ipp.base.PsiElementPredicate;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class MergeElseIfIntention extends Intention {
@Override
@NotNull
public PsiElementPredicate getElementPredicate() {
return new MergeElseIfPredicate();
}
@Override
public void processIntention(PsiElement element) {
final PsiJavaToken token = (PsiJavaToken)element;
final PsiIfStatement parentStatement = (PsiIfStatement)token.getParent();
assert parentStatement != null;
final PsiBlockStatement elseBranch = (PsiBlockStatement)parentStatement.getElseBranch();
assert elseBranch != null;
final PsiElement lastChild = elseBranch.getLastChild();
final PsiCodeBlock elseBranchBlock = elseBranch.getCodeBlock();
final PsiStatement elseBranchContents = elseBranchBlock.getStatements()[0];
final PsiElement grandParent = parentStatement.getParent();
if (lastChild instanceof PsiComment) {
addElementAndPrevWhiteSpace(lastChild, grandParent, parentStatement);
}
final List<PsiComment> before = new ArrayList<>(1);
final List<PsiComment> after = new ArrayList<>(1);
collectComments(elseBranchContents, before, after);
for (PsiComment comment : before) {
addElementAndPrevWhiteSpace(comment, parentStatement, token);
}
for (PsiComment comment : after) {
grandParent.addAfter(comment, parentStatement);
}
PsiReplacementUtil.replaceStatement(elseBranch, elseBranchContents.getText());
}
private static void addElementAndPrevWhiteSpace(PsiElement element, PsiElement container, PsiElement anchor) {
final PsiElement sibling = element.getPrevSibling();
container.addAfter(element, anchor);
if (sibling instanceof PsiWhiteSpace) {
container.addAfter(sibling, anchor);
}
}
/**
* Before comments are added in reverse order of appearance in the code.
*/
private static void collectComments(PsiStatement statement, List<? super PsiComment> before, List<? super PsiComment> after) {
PsiElement prevSibling = statement.getPrevSibling();
while (prevSibling != null) {
if (prevSibling instanceof PsiComment) {
before.add((PsiComment)prevSibling);
}
prevSibling = prevSibling.getPrevSibling();
}
PsiElement nextSibing = statement.getNextSibling();
while (nextSibing != null) {
if (nextSibing instanceof PsiComment) {
after.add((PsiComment)nextSibing);
}
nextSibing = nextSibing.getNextSibling();
}
}
} | apache-2.0 |
olamy/archiva | archiva-modules/archiva-base/archiva-repository-api/src/main/java/org/apache/archiva/repository/RemoteRepository.java | 2280 | package org.apache.archiva.repository;
/*
* 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.
*/
import java.time.Duration;
import java.util.Map;
/**
* This represents a repository that is not fully managed by archiva. Its some kind of proxy that
* forwards requests to the remote repository and is able to cache artifacts locally.
*/
public interface RemoteRepository extends Repository {
/**
* Returns the interface to access the content of the repository.
* @return
*/
RemoteRepositoryContent getContent();
/**
* Returns the credentials used to login to the remote repository.
* @return the credentials, null if not set.
*/
RepositoryCredentials getLoginCredentials();
/**
* Returns the path relative to the root url of the repository that should be used
* to check the availability of the repository.
* @return The check path, null if not set.
*/
String getCheckPath();
/**
* Returns additional parameters, that are used for accessing the remote repository.
* @return A map of key, value pairs.
*/
Map<String,String> getExtraParameters();
/**
* Returns extra headers that are added to the request to the remote repository.
* @return
*/
Map<String,String> getExtraHeaders();
/**
* Returns the time duration, after that the request is aborted and a error is returned, if the remote repository
* does not respond.
* @return The timeout.
*/
Duration getTimeout();
}
| apache-2.0 |
apache/karaf-eik | plugins/org.apache.karaf.eik.ui/src/main/java/org/apache/karaf/eik/ui/model/AbstractContentModel.java | 1766 | /*
* 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.karaf.eik.ui.model;
import org.apache.karaf.eik.core.KarafPlatformModel;
import org.apache.karaf.eik.ui.IKarafProject;
import org.eclipse.core.runtime.PlatformObject;
public abstract class AbstractContentModel extends PlatformObject implements ContentModel {
protected final KarafPlatformModel karafPlatformModel;
protected final IKarafProject project;
public AbstractContentModel(final IKarafProject project) {
this.project = project;
this.karafPlatformModel = (KarafPlatformModel) project.getAdapter(KarafPlatformModel.class);
}
@Override
public Object getAdapter(@SuppressWarnings("rawtypes") final Class adapter) {
if (KarafPlatformModel.class.equals(adapter)) {
return karafPlatformModel;
} else {
return super.getAdapter(adapter);
}
}
@Override
public Object getParent() {
return project.getProjectHandle();
}
}
| apache-2.0 |
tombujok/hazelcast | hazelcast/src/main/java/com/hazelcast/client/impl/protocol/task/cache/Pre38CacheAddInvalidationListenerTask.java | 4799 | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.impl.protocol.task.cache;
import com.hazelcast.cache.impl.CacheContext;
import com.hazelcast.cache.impl.CacheService;
import com.hazelcast.client.ClientEndpoint;
import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.codec.CacheAddInvalidationListenerCodec;
import com.hazelcast.client.impl.protocol.task.AbstractCallableMessageTask;
import com.hazelcast.instance.Node;
import com.hazelcast.internal.nearcache.impl.invalidation.Invalidation;
import com.hazelcast.nio.Connection;
import com.hazelcast.nio.serialization.Data;
import java.security.Permission;
import java.util.List;
import java.util.UUID;
public class Pre38CacheAddInvalidationListenerTask
extends AbstractCallableMessageTask<CacheAddInvalidationListenerCodec.RequestParameters> {
public Pre38CacheAddInvalidationListenerTask(ClientMessage clientMessage, Node node, Connection connection) {
super(clientMessage, node, connection);
}
@Override
protected Object call() {
ClientEndpoint endpoint = getEndpoint();
CacheService cacheService = getService(CacheService.SERVICE_NAME);
CacheContext cacheContext = cacheService.getOrCreateCacheContext(parameters.name);
Pre38NearCacheInvalidationListener listener
= new Pre38NearCacheInvalidationListener(endpoint, cacheContext, nodeEngine.getLocalMember().getUuid());
String registrationId =
cacheService.addInvalidationListener(parameters.name, listener, parameters.localOnly);
endpoint.addListenerDestroyAction(CacheService.SERVICE_NAME, parameters.name, registrationId);
return registrationId;
}
/**
* This listener is here to be used with server versions < 3.8.
* Because new improvements for Near Cache eventual consistency cannot work with server versions < 3.8.
*/
private final class Pre38NearCacheInvalidationListener extends AbstractCacheClientNearCacheInvalidationListener {
Pre38NearCacheInvalidationListener(ClientEndpoint endpoint, CacheContext cacheContext, String localMemberUuid) {
super(endpoint, cacheContext, localMemberUuid);
}
@Override
protected ClientMessage encodeBatchInvalidation(String name, List<Data> keys, List<String> sourceUuids,
List<UUID> partitionUuids, List<Long> sequences) {
return CacheAddInvalidationListenerCodec.encodeCacheBatchInvalidationEvent(name, keys, sourceUuids,
partitionUuids, sequences);
}
@Override
protected ClientMessage encodeSingleInvalidation(String name, Data key, String sourceUuid,
UUID partitionUuid, long sequence) {
return CacheAddInvalidationListenerCodec.encodeCacheInvalidationEvent(name, key, sourceUuid,
partitionUuid, sequence);
}
@Override
protected void sendMessageWithOrderKey(ClientMessage clientMessage, Object orderKey) {
sendClientMessage(orderKey, clientMessage);
}
@Override
protected boolean canSendInvalidation(Invalidation invalidation) {
return !endpoint.getUuid().equals(invalidation.getSourceUuid());
}
}
@Override
protected CacheAddInvalidationListenerCodec.RequestParameters decodeClientMessage(ClientMessage clientMessage) {
return CacheAddInvalidationListenerCodec.decodeRequest(clientMessage);
}
@Override
protected ClientMessage encodeResponse(Object response) {
return CacheAddInvalidationListenerCodec.encodeResponse((String) response);
}
@Override
public String getDistributedObjectName() {
return parameters.name;
}
@Override
public String getMethodName() {
return null;
}
@Override
public Object[] getParameters() {
return null;
}
@Override
public String getServiceName() {
return CacheService.SERVICE_NAME;
}
@Override
public Permission getRequiredPermission() {
return null;
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-reseller/v1/1.29.2/com/google/api/services/reseller/model/ChangePlanRequest.java | 8389 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.reseller.model;
/**
* JSON template for the ChangePlan rpc request.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Enterprise Apps Reseller API. For a detailed
* explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class ChangePlanRequest extends com.google.api.client.json.GenericJson {
/**
* Google-issued code (100 char max) for discounted pricing on subscription plans. Deal code must
* be included in changePlan request in order to receive discounted rate. This property is
* optional. If a deal code has already been added to a subscription, this property may be left
* empty and the existing discounted rate will still apply (if not empty, only provide the deal
* code that is already present on the subscription). If a deal code has never been added to a
* subscription and this property is left blank, regular pricing will apply.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String dealCode;
/**
* Identifies the resource as a subscription change plan request. Value:
* subscriptions#changePlanRequest
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* The planName property is required. This is the name of the subscription's payment plan. For
* more information about the Google payment plans, see API concepts.
*
* Possible values are: - ANNUAL_MONTHLY_PAY - The annual commitment plan with monthly payments
* Caution: ANNUAL_MONTHLY_PAY is returned as ANNUAL in all API responses. - ANNUAL_YEARLY_PAY -
* The annual commitment plan with yearly payments - FLEXIBLE - The flexible plan - TRIAL -
* The 30-day free trial plan
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String planName;
/**
* This is an optional property. This purchase order (PO) information is for resellers to use for
* their company tracking usage. If a purchaseOrderId value is given it appears in the API
* responses and shows up in the invoice. The property accepts up to 80 plain text characters.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String purchaseOrderId;
/**
* This is a required property. The seats property is the number of user seat licenses.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Seats seats;
/**
* Google-issued code (100 char max) for discounted pricing on subscription plans. Deal code must
* be included in changePlan request in order to receive discounted rate. This property is
* optional. If a deal code has already been added to a subscription, this property may be left
* empty and the existing discounted rate will still apply (if not empty, only provide the deal
* code that is already present on the subscription). If a deal code has never been added to a
* subscription and this property is left blank, regular pricing will apply.
* @return value or {@code null} for none
*/
public java.lang.String getDealCode() {
return dealCode;
}
/**
* Google-issued code (100 char max) for discounted pricing on subscription plans. Deal code must
* be included in changePlan request in order to receive discounted rate. This property is
* optional. If a deal code has already been added to a subscription, this property may be left
* empty and the existing discounted rate will still apply (if not empty, only provide the deal
* code that is already present on the subscription). If a deal code has never been added to a
* subscription and this property is left blank, regular pricing will apply.
* @param dealCode dealCode or {@code null} for none
*/
public ChangePlanRequest setDealCode(java.lang.String dealCode) {
this.dealCode = dealCode;
return this;
}
/**
* Identifies the resource as a subscription change plan request. Value:
* subscriptions#changePlanRequest
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* Identifies the resource as a subscription change plan request. Value:
* subscriptions#changePlanRequest
* @param kind kind or {@code null} for none
*/
public ChangePlanRequest setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* The planName property is required. This is the name of the subscription's payment plan. For
* more information about the Google payment plans, see API concepts.
*
* Possible values are: - ANNUAL_MONTHLY_PAY - The annual commitment plan with monthly payments
* Caution: ANNUAL_MONTHLY_PAY is returned as ANNUAL in all API responses. - ANNUAL_YEARLY_PAY -
* The annual commitment plan with yearly payments - FLEXIBLE - The flexible plan - TRIAL -
* The 30-day free trial plan
* @return value or {@code null} for none
*/
public java.lang.String getPlanName() {
return planName;
}
/**
* The planName property is required. This is the name of the subscription's payment plan. For
* more information about the Google payment plans, see API concepts.
*
* Possible values are: - ANNUAL_MONTHLY_PAY - The annual commitment plan with monthly payments
* Caution: ANNUAL_MONTHLY_PAY is returned as ANNUAL in all API responses. - ANNUAL_YEARLY_PAY -
* The annual commitment plan with yearly payments - FLEXIBLE - The flexible plan - TRIAL -
* The 30-day free trial plan
* @param planName planName or {@code null} for none
*/
public ChangePlanRequest setPlanName(java.lang.String planName) {
this.planName = planName;
return this;
}
/**
* This is an optional property. This purchase order (PO) information is for resellers to use for
* their company tracking usage. If a purchaseOrderId value is given it appears in the API
* responses and shows up in the invoice. The property accepts up to 80 plain text characters.
* @return value or {@code null} for none
*/
public java.lang.String getPurchaseOrderId() {
return purchaseOrderId;
}
/**
* This is an optional property. This purchase order (PO) information is for resellers to use for
* their company tracking usage. If a purchaseOrderId value is given it appears in the API
* responses and shows up in the invoice. The property accepts up to 80 plain text characters.
* @param purchaseOrderId purchaseOrderId or {@code null} for none
*/
public ChangePlanRequest setPurchaseOrderId(java.lang.String purchaseOrderId) {
this.purchaseOrderId = purchaseOrderId;
return this;
}
/**
* This is a required property. The seats property is the number of user seat licenses.
* @return value or {@code null} for none
*/
public Seats getSeats() {
return seats;
}
/**
* This is a required property. The seats property is the number of user seat licenses.
* @param seats seats or {@code null} for none
*/
public ChangePlanRequest setSeats(Seats seats) {
this.seats = seats;
return this;
}
@Override
public ChangePlanRequest set(String fieldName, Object value) {
return (ChangePlanRequest) super.set(fieldName, value);
}
@Override
public ChangePlanRequest clone() {
return (ChangePlanRequest) super.clone();
}
}
| apache-2.0 |
Squeegee/batik | test-sources/org/apache/batik/ext/awt/geom/Messages.java | 2248 | /*
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.batik.ext.awt.geom;
import java.util.Locale;
import java.util.MissingResourceException;
import org.apache.batik.i18n.LocalizableSupport;
/**
* This class manages the message for the test.svg module.
*
* @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a>
* @version $Id$
*/
public class Messages {
/**
* This class does not need to be instantiated.
*/
protected Messages() { }
/**
* The error messages bundle class name.
*/
protected static final String RESOURCES =
"org.apache.batik.ext.awt.geom.resources.TestMessages";
/**
* The localizable support for the error messages.
*/
protected static LocalizableSupport localizableSupport =
new LocalizableSupport(RESOURCES);
/**
* Implements {@link org.apache.batik.i18n.Localizable#setLocale(Locale)}.
*/
public static void setLocale(Locale l) {
localizableSupport.setLocale(l);
}
/**
* Implements {@link org.apache.batik.i18n.Localizable#getLocale()}.
*/
public static Locale getLocale() {
return localizableSupport.getLocale();
}
/**
* Implements {@link
* org.apache.batik.i18n.Localizable#formatMessage(String,Object[])}.
*/
public static String formatMessage(String key, Object[] args)
throws MissingResourceException {
return localizableSupport.formatMessage(key, args);
}
}
| apache-2.0 |
sagar15795/incubator-taverna-mobile | app/src/main/java/org/apache/taverna/mobile/data/model/License.java | 4337 | /*
* 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.taverna.mobile.data.model;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import android.os.Parcel;
import android.os.Parcelable;
public class License implements Parcelable {
@Attribute(name = "resource", required = false)
private String resource;
@Attribute(name = "uri", required = false)
private String uri;
@Attribute(name = "id", required = false)
private String id;
@Element(name = "id", required = false)
private String elementId;
@Element(name = "unique-name", required = false)
private String uniqueName;
@Element(name = "title", required = false)
private String title;
@Element(name = "description", required = false)
private String description;
@Element(name = "url", required = false)
private String url;
@Element(name = "created-at", required = false)
private String createdAt;
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getElementId() {
return elementId;
}
public void setElementId(String elementId) {
this.elementId = elementId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUniqueName() {
return uniqueName;
}
public void setUniqueName(String uniqueName) {
this.uniqueName = uniqueName;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.resource);
dest.writeString(this.uri);
dest.writeString(this.id);
dest.writeString(this.elementId);
dest.writeString(this.uniqueName);
dest.writeString(this.title);
dest.writeString(this.description);
dest.writeString(this.url);
dest.writeString(this.createdAt);
}
public License() {
}
protected License(Parcel in) {
this.resource = in.readString();
this.uri = in.readString();
this.id = in.readString();
this.elementId = in.readString();
this.uniqueName = in.readString();
this.title = in.readString();
this.description = in.readString();
this.url = in.readString();
this.createdAt = in.readString();
}
public static final Parcelable.Creator<License> CREATOR = new Parcelable.Creator<License>() {
@Override
public License createFromParcel(Parcel source) {
return new License(source);
}
@Override
public License[] newArray(int size) {
return new License[size];
}
};
}
| apache-2.0 |
thuckechsu/MaterialDesignLibrary | src/main/java/com/gc/materialdesign/views/Card.java | 1572 | package com.gc.materialdesign.views;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.widget.TextView;
import com.gc.materialdesign.R;
public class Card extends CustomView {
TextView textButton;
int paddingTop,paddingBottom, paddingLeft, paddingRight;
int backgroundColor = Color.parseColor("#FFFFFF");
public Card(Context context, AttributeSet attrs) {
super(context, attrs);
setAttributes(attrs);
}
// Set atributtes of XML to View
protected void setAttributes(AttributeSet attrs){
setBackgroundResource(R.drawable.background_button_rectangle);
//Set background Color
// Color by resource
int bacgroundColor = attrs.getAttributeResourceValue(ANDROIDXML,"background",-1);
if(bacgroundColor != -1){
setBackgroundColor(getResources().getColor(bacgroundColor));
}else{
// Color by hexadecimal
String background = attrs.getAttributeValue(ANDROIDXML,"background");
if(background != null)
setBackgroundColor(Color.parseColor(background));
else
setBackgroundColor(this.backgroundColor);
}
}
// Set color of background
public void setBackgroundColor(int color){
this.backgroundColor = color;
if(isEnabled())
beforeBackground = backgroundColor;
LayerDrawable layer = (LayerDrawable) getBackground();
GradientDrawable shape = (GradientDrawable) layer.findDrawableByLayerId(R.id.shape_bacground);
shape.setColor(backgroundColor);
}
}
| apache-2.0 |
facebook/buck | test/com/facebook/buck/core/starlark/rule/attr/impl/StringAttributeTest.java | 3966 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.buck.core.starlark.rule.attr.impl;
import static org.junit.Assert.assertEquals;
import com.facebook.buck.core.cell.TestCellPathResolver;
import com.facebook.buck.core.cell.nameresolver.CellNameResolver;
import com.facebook.buck.core.model.UnconfiguredTargetConfiguration;
import com.facebook.buck.core.path.ForwardRelativePath;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.rules.coercer.CoerceFailedException;
import com.google.common.collect.ImmutableList;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class StringAttributeTest {
private final FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
private final CellNameResolver cellRoots =
TestCellPathResolver.get(filesystem).getCellNameResolver();
@Rule public ExpectedException expected = ExpectedException.none();
@Test
public void coercesStringsProperly() throws CoerceFailedException {
StringAttribute attr = ImmutableStringAttribute.of("foobaz", "", true, ImmutableList.of());
String coerced =
attr.getValue(
cellRoots,
filesystem,
ForwardRelativePath.of(""),
UnconfiguredTargetConfiguration.INSTANCE,
UnconfiguredTargetConfiguration.INSTANCE,
"bar");
assertEquals("bar", coerced);
}
@Test
public void failsMandatoryCoercionProperly() throws CoerceFailedException {
expected.expect(CoerceFailedException.class);
StringAttribute attr = ImmutableStringAttribute.of("foobaz", "", true, ImmutableList.of());
attr.getValue(
cellRoots,
filesystem,
ForwardRelativePath.of(""),
UnconfiguredTargetConfiguration.INSTANCE,
UnconfiguredTargetConfiguration.INSTANCE,
1);
}
@Test
public void succeedsIfValueInArray() throws CoerceFailedException {
StringAttribute attr =
ImmutableStringAttribute.of("foobaz", "", true, ImmutableList.of("foo", "bar", "baz"));
String value =
attr.getValue(
cellRoots,
filesystem,
ForwardRelativePath.of(""),
UnconfiguredTargetConfiguration.INSTANCE,
UnconfiguredTargetConfiguration.INSTANCE,
"bar");
assertEquals("bar", value);
}
@Test
public void allowsAnyValueIfValuesIsEmptyList() throws CoerceFailedException {
StringAttribute attr = ImmutableStringAttribute.of("foobaz", "", true, ImmutableList.of());
String value =
attr.getValue(
cellRoots,
filesystem,
ForwardRelativePath.of(""),
UnconfiguredTargetConfiguration.INSTANCE,
UnconfiguredTargetConfiguration.INSTANCE,
"bar");
assertEquals("bar", value);
}
@Test
public void failsIfValueNotInArray() throws CoerceFailedException {
expected.expect(CoerceFailedException.class);
expected.expectMessage("must be one of 'foo', 'baz' instead of 'bar'");
StringAttribute attr =
ImmutableStringAttribute.of("foobaz", "", true, ImmutableList.of("foo", "baz"));
attr.getValue(
cellRoots,
filesystem,
ForwardRelativePath.of(""),
UnconfiguredTargetConfiguration.INSTANCE,
UnconfiguredTargetConfiguration.INSTANCE,
"bar");
}
}
| apache-2.0 |
facebook/buck | test/com/facebook/buck/cli/endtoend/BuildEndToEndTest.java | 13250 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.buck.cli.endtoend;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.core.cell.name.CanonicalCellName;
import com.facebook.buck.core.filesystems.AbsPath;
import com.facebook.buck.core.model.BuildId;
import com.facebook.buck.doctor.BuildLogHelper;
import com.facebook.buck.doctor.config.BuildLogEntry;
import com.facebook.buck.io.filesystem.BuckPaths;
import com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemFactory;
import com.facebook.buck.testutil.PlatformUtils;
import com.facebook.buck.testutil.ProcessResult;
import com.facebook.buck.testutil.endtoend.EndToEndEnvironment;
import com.facebook.buck.testutil.endtoend.EndToEndRunner;
import com.facebook.buck.testutil.endtoend.EndToEndTestDescriptor;
import com.facebook.buck.testutil.endtoend.EndToEndWorkspace;
import com.facebook.buck.testutil.endtoend.Environment;
import com.facebook.buck.testutil.endtoend.EnvironmentFor;
import com.facebook.buck.testutil.endtoend.ToggleState;
import com.facebook.buck.util.ExitCode;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(EndToEndRunner.class)
public class BuildEndToEndTest {
@Environment
public static EndToEndEnvironment getBaseEnvironment() {
return new EndToEndEnvironment()
.withCommand("build")
.addLocalConfigSet(
ImmutableMap.of("parser", ImmutableMap.of("default_build_file_syntax", "SKYLARK")))
.addLocalConfigSet(
ImmutableMap.of("parser", ImmutableMap.of("default_build_file_syntax", "PYTHON_DSL")));
}
@EnvironmentFor(testNames = {"shouldRewriteFailureMessagesAndAppendThem"})
public static EndToEndEnvironment setTargetPathThatCallsFail() {
return getBaseEnvironment()
.addTemplates("cli")
.withTargets("//parse_failure/fail_message:fail");
}
@EnvironmentFor(testNames = {"shouldRewriteFailureMessagesForInvalidTargets"})
public static EndToEndEnvironment setTargetPathThatHasBadTargets() {
return getBaseEnvironment()
.addTemplates("cli")
.withTargets("//parse_failure/invalid_deps:main");
}
@EnvironmentFor(testNames = {"testMissingTargetLocationIsShowAfterRebuild"})
public static EndToEndEnvironment setTargetPathWithMissingDep() {
return getBaseEnvironment()
.addTemplates("missing_dep")
.withTargets("//:a")
.withBuckdToggled(ToggleState.ON);
}
@EnvironmentFor(testNames = {"changingVersionShouldClearBuckOutWithConfiguredBuckOutDir"})
public static EndToEndEnvironment setTargetPathWithBinaryBuiltFromGenrule() {
return getBaseEnvironment()
.addTemplates("cxx_dependent_on_py")
.withBuckdToggled(ToggleState.ON);
}
@EnvironmentFor(testNames = {"printsErrorWhenBuckConfigIsMissing", "allowsRelativeBuildTargets"})
public static EndToEndEnvironment setSimpleEnv() {
return getBaseEnvironment().addTemplates("cli");
}
@EnvironmentFor(testNames = {"nestedBuildsUseDifferentUUID"})
public static EndToEndEnvironment setupNestedBuildsEnv() {
return getBaseEnvironment().addTemplates("nested_build");
}
@EnvironmentFor(testNames = {"handlesNonUtf8OnStdFds"})
public static EndToEndEnvironment setupHandlesNonUtf8OnStdFds() {
return getBaseEnvironment().withBuckdToggled(ToggleState.ON).addTemplates("cli");
}
@Test
public void allowsRelativeBuildTargets(EndToEndTestDescriptor test, EndToEndWorkspace workspace)
throws Throwable {
workspace.addPremadeTemplate("cli");
workspace.setup();
ImmutableMap<String, Path> simpleBinPath =
workspace.buildAndReturnOutputs("run/simple_bin:main_py");
workspace.runBuckCommand("run", "run/simple_bin:main_py").assertSuccess();
workspace.setRelativeWorkingDirectory(Paths.get("run"));
ImmutableMap<String, Path> relativeSimpleBinPath =
workspace.buildAndReturnOutputs("simple_bin:main_py");
ImmutableMap<String, Path> targetsRelativeSimpleBinPath =
workspace.runCommandAndReturnOutputs("targets", "simple_bin:main_py");
workspace.runBuckCommand("run", "simple_bin:main_py").assertSuccess();
assertEquals(simpleBinPath, relativeSimpleBinPath);
assertEquals(simpleBinPath, targetsRelativeSimpleBinPath);
}
@Test
public void shouldRewriteFailureMessagesAndAppendThem(
EndToEndTestDescriptor test, EndToEndWorkspace workspace) throws Exception {
workspace.addBuckConfigLocalOption(
"ui",
"error_message_augmentations",
"\"name ([-\\\\w]*) provided\" => \"You pizza'd when you should have french fried on $1\"");
Pattern expected =
Pattern.compile(
"Invalid name fail-py provided$.*^You pizza'd when you should have french fried on fail-py",
Pattern.MULTILINE | Pattern.DOTALL);
ProcessResult result = workspace.runBuckCommand(test);
result.assertExitCode(ExitCode.PARSE_ERROR);
assertTrue(
String.format("'%s' was not contained in '%s'", expected.pattern(), result.getStderr()),
expected.matcher(result.getStderr()).find());
}
@Test
public void shouldRewriteFailureMessagesForInvalidTargets(
EndToEndTestDescriptor test, EndToEndWorkspace workspace) throws Exception {
workspace.addBuckConfigLocalOption(
"ui",
"error_message_augmentations",
"\"The rule (//\\\\S+)-cxx could not be found.\" => \"Please make sure that $1 "
+ "is a cxx library. If it is not, add it to extra_deps instead\"");
Pattern expected =
Pattern.compile(
"The rule //parse_failure/invalid_deps:main-cxx could not be found\\..*"
+ "Please make sure that //parse_failure/invalid_deps:main is a cxx library. "
+ "If it is not, add it to extra_deps instead",
Pattern.MULTILINE | Pattern.DOTALL);
ProcessResult result = workspace.runBuckCommand(test);
result.assertFailure();
assertTrue(
String.format("'%s' was not contained in '%s'", expected.pattern(), result.getStderr()),
expected.matcher(result.getStderr()).find());
}
@Test
public void testMissingTargetLocationIsShowAfterRebuild(
EndToEndTestDescriptor test, EndToEndWorkspace workspace) throws Exception {
ProcessResult result = workspace.runBuckCommand(test);
result.assertFailure();
assertThat(
result.getStderr(),
containsString(
"No build file at missing/BUCK when resolving target //missing:dep.\n"
+ "\n"
+ "This error happened while trying to get dependency '//missing:dep' of target '//:a'"));
result = workspace.runBuckCommand(test);
result.assertFailure();
assertThat(
result.getStderr(),
containsString(
"No build file at missing/BUCK when resolving target //missing:dep.\n"
+ "\n"
+ "This error happened while trying to get dependency '//missing:dep' of target '//:a'"));
}
@Test
public void changingVersionShouldClearBuckOutWithConfiguredBuckOutDir(
EndToEndTestDescriptor test, EndToEndWorkspace workspace) throws Throwable {
for (String template : test.getTemplateSet()) {
workspace.addPremadeTemplate(template);
}
ProcessResult result = workspace.runBuckCommand("run", "@mode/opt", "//main_bin:main_bin");
result.assertSuccess();
result = workspace.runBuckCommand("run", "@mode/dev", "//main_bin:main_bin");
result.assertSuccess();
Path optVersion =
workspace.getDestPath().resolve(Paths.get("buck-out", "opt", ".currentversion"));
Path devVersion =
workspace.getDestPath().resolve(Paths.get("buck-out", "dev", ".currentversion"));
Path optBin =
workspace
.getDestPath()
.resolve(Paths.get("buck-out", "opt", "gen", "main_bin", "main_bin"));
Path devBin =
workspace
.getDestPath()
.resolve(Paths.get("buck-out", "dev", "gen", "main_bin", "main_bin"));
assertTrue(Files.exists(optVersion));
assertTrue(Files.exists(devVersion));
assertTrue(Files.exists(optBin));
assertTrue(Files.exists(devBin));
Files.delete(optBin);
Files.delete(devBin);
result = workspace.runBuckCommand("run", "@mode/opt", "//main_bin:main_bin");
result.assertFailure();
result = workspace.runBuckCommand("run", "@mode/dev", "//main_bin:main_bin");
result.assertFailure();
Files.delete(optVersion);
Files.delete(devVersion);
result = workspace.runBuckCommand("run", "@mode/dev", "//main_bin:main_bin");
result.assertSuccess();
result = workspace.runBuckCommand("run", "@mode/opt", "//main_bin:main_bin");
result.assertSuccess();
}
@Test
public void printsErrorWhenBuckConfigIsMissing(
EndToEndTestDescriptor test, EndToEndWorkspace workspace) throws Throwable {
workspace.setup();
String[] expected =
new String[] {
"This does not appear to be the root of a Buck project. Please 'cd'",
"to the root of your project before running buck. If this really is",
"the root of your project, run",
"'touch .buckconfig'",
"and then re-run your buck command."
};
ProcessResult result = workspace.runBuckCommand("query", "//:");
result.assertExitCode(ExitCode.COMMANDLINE_ERROR);
for (String line : expected) {
assertThat(result.getStderr(), containsString(line));
}
assertThat(result.getStderr(), not(containsString("NoBuckConfigFoundException")));
}
@Test
public void nestedBuildsUseDifferentUUID(EndToEndTestDescriptor test, EndToEndWorkspace workspace)
throws Throwable {
workspace.setup();
ImmutableList<String> fullBuckCommand =
PlatformUtils.getForPlatform().getBuckCommandBuilder().build();
String buckCommand = fullBuckCommand.get(fullBuckCommand.size() - 1);
workspace
.runBuckCommand(
false,
ImmutableMap.of("BUCK_BUILD_ID", "1234-5678"),
test.getTemplateSet(),
"build",
"-c",
"user.buck_path=" + buckCommand,
"//:query")
.assertSuccess();
ImmutableList<BuildLogEntry> helper =
new BuildLogHelper(
new DefaultProjectFilesystemFactory()
.createProjectFilesystem(
CanonicalCellName.rootCell(),
AbsPath.of(workspace.getDestPath()),
BuckPaths.DEFAULT_BUCK_OUT_INCLUDE_TARGET_CONFIG_HASH))
.getBuildLogs();
assertEquals(2, helper.size());
Optional<BuildLogEntry> buildCommand =
helper.stream()
.filter(
log -> {
Optional<List<String>> args = log.getCommandArgs();
return args.isPresent()
&& args.get().containsAll(ImmutableList.of("build", "//:query"));
})
.findFirst();
Optional<BuildLogEntry> queryCommand =
helper.stream()
.filter(
log -> {
Optional<List<String>> args = log.getCommandArgs();
return args.isPresent()
&& args.get().containsAll(ImmutableList.of("query", "//:query"));
})
.findFirst();
assertTrue("Build command was not found in logs", buildCommand.isPresent());
assertTrue("Query command was not found in logs", queryCommand.isPresent());
assertEquals(Optional.of(new BuildId("1234-5678")), buildCommand.get().getBuildId());
assertNotEquals(Optional.of(new BuildId("1234-5678")), queryCommand.get().getBuildId());
}
@Test
public void handlesNonUtf8OnStdFds(EndToEndTestDescriptor test, EndToEndWorkspace workspace)
throws Throwable {
for (String template : test.getTemplateSet()) {
workspace.addPremadeTemplate(template);
}
workspace.setup();
ProcessResult res = workspace.runBuckCommand(true, "build", "//bad_utf8:").assertFailure();
assertThat(res.getStderr(), not(containsString("UnicodeDecodeError")));
assertThat(res.getStderr(), containsString("foo bar baz"));
}
}
| apache-2.0 |
okalmanRH/jboss-activemq-artemis | tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/openwire/amq/ProducerFlowControlTest.java | 13196 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.openwire.amq;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.settings.impl.AddressFullMessagePolicy;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.tests.integration.openwire.BasicOpenWireTest;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.transport.tcp.TcpTransport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* adapted from: org.apache.activemq.ProducerFlowControlTest
*/
public class ProducerFlowControlTest extends BasicOpenWireTest {
ActiveMQQueue queueA = new ActiveMQQueue("QUEUE.A");
ActiveMQQueue queueB = new ActiveMQQueue("QUEUE.B");
protected ActiveMQConnection flowControlConnection;
// used to test sendFailIfNoSpace on SystemUsage
protected final AtomicBoolean gotResourceException = new AtomicBoolean(false);
private Thread asyncThread = null;
@Test
public void test2ndPublisherWithProducerWindowSendConnectionThatIsBlocked() throws Exception {
factory.setProducerWindowSize(1024 * 64);
flowControlConnection = (ActiveMQConnection) factory.createConnection();
flowControlConnection.start();
Session session = flowControlConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queueB);
// Test sending to Queue A
// 1 few sends should not block until the producer window is used up.
fillQueue(queueA);
// Test sending to Queue B it should not block since the connection
// should not be blocked.
CountDownLatch pubishDoneToQeueuB = asyncSendTo(queueB, "Message 1");
assertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS));
TextMessage msg = (TextMessage) consumer.receive();
assertEquals("Message 1", msg.getText());
msg.acknowledge();
pubishDoneToQeueuB = asyncSendTo(queueB, "Message 2");
assertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS));
msg = (TextMessage) consumer.receive();
assertEquals("Message 2", msg.getText());
msg.acknowledge();
consumer.close();
}
@Test
public void testPublisherRecoverAfterBlock() throws Exception {
flowControlConnection = (ActiveMQConnection) factory.createConnection();
flowControlConnection.start();
final Session session = flowControlConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
final MessageProducer producer = session.createProducer(queueA);
final AtomicBoolean done = new AtomicBoolean(true);
final AtomicBoolean keepGoing = new AtomicBoolean(true);
Thread thread = new Thread("Filler") {
int i;
@Override
public void run() {
while (keepGoing.get()) {
done.set(false);
try {
producer.send(session.createTextMessage("Test message " + ++i));
} catch (JMSException e) {
break;
}
}
}
};
thread.start();
waitForBlockedOrResourceLimit(done);
// after receiveing messges, producer should continue sending messages
// (done == false)
MessageConsumer consumer = session.createConsumer(queueA);
TextMessage msg;
for (int idx = 0; idx < 5; ++idx) {
msg = (TextMessage) consumer.receive(1000);
System.out.println("received: " + idx + ", msg: " + msg.getJMSMessageID());
msg.acknowledge();
}
Thread.sleep(1000);
keepGoing.set(false);
consumer.close();
assertFalse("producer has resumed", done.get());
}
@Test
public void testAsyncPublisherRecoverAfterBlock() throws Exception {
factory.setProducerWindowSize(1024 * 5);
factory.setUseAsyncSend(true);
flowControlConnection = (ActiveMQConnection) factory.createConnection();
flowControlConnection.start();
final Session session = flowControlConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
final MessageProducer producer = session.createProducer(queueA);
final AtomicBoolean done = new AtomicBoolean(true);
final AtomicBoolean keepGoing = new AtomicBoolean(true);
Thread thread = new Thread("Filler") {
int i;
@Override
public void run() {
while (keepGoing.get()) {
done.set(false);
try {
producer.send(session.createTextMessage("Test message " + ++i));
} catch (JMSException e) {
}
}
}
};
thread.start();
waitForBlockedOrResourceLimit(done);
// after receiveing messges, producer should continue sending messages
// (done == false)
MessageConsumer consumer = session.createConsumer(queueA);
TextMessage msg;
for (int idx = 0; idx < 5; ++idx) {
msg = (TextMessage) consumer.receive(1000);
assertNotNull("Got a message", msg);
System.out.println("received: " + idx + ", msg: " + msg.getJMSMessageID());
msg.acknowledge();
}
Thread.sleep(1000);
keepGoing.set(false);
consumer.close();
assertFalse("producer has resumed", done.get());
}
@Test
public void test2ndPublisherWithSyncSendConnectionThatIsBlocked() throws Exception {
factory.setAlwaysSyncSend(true);
flowControlConnection = (ActiveMQConnection) factory.createConnection();
flowControlConnection.start();
Session session = flowControlConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queueB);
// Test sending to Queue A
// 1st send should not block. But the rest will.
fillQueue(queueA);
// Test sending to Queue B it should not block.
CountDownLatch pubishDoneToQeueuB = asyncSendTo(queueB, "Message 1");
assertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS));
TextMessage msg = (TextMessage) consumer.receive();
assertEquals("Message 1", msg.getText());
msg.acknowledge();
pubishDoneToQeueuB = asyncSendTo(queueB, "Message 2");
assertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS));
msg = (TextMessage) consumer.receive();
assertEquals("Message 2", msg.getText());
msg.acknowledge();
consumer.close();
}
@Test
public void testSimpleSendReceive() throws Exception {
factory.setAlwaysSyncSend(true);
flowControlConnection = (ActiveMQConnection) factory.createConnection();
flowControlConnection.start();
Session session = flowControlConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queueA);
// Test sending to Queue B it should not block.
CountDownLatch pubishDoneToQeueuA = asyncSendTo(queueA, "Message 1");
assertTrue(pubishDoneToQeueuA.await(2, TimeUnit.SECONDS));
TextMessage msg = (TextMessage) consumer.receive();
assertEquals("Message 1", msg.getText());
msg.acknowledge();
pubishDoneToQeueuA = asyncSendTo(queueA, "Message 2");
assertTrue(pubishDoneToQeueuA.await(2, TimeUnit.SECONDS));
msg = (TextMessage) consumer.receive();
assertEquals("Message 2", msg.getText());
msg.acknowledge();
consumer.close();
}
@Test
public void test2ndPublisherWithStandardConnectionThatIsBlocked() throws Exception {
flowControlConnection = (ActiveMQConnection) factory.createConnection();
flowControlConnection.start();
// Test sending to Queue A
// 1st send should not block.
fillQueue(queueA);
// Test sending to Queue B it should block.
// Since even though the it's queue limits have not been reached, the
// connection
// is blocked.
CountDownLatch pubishDoneToQeueuB = asyncSendTo(queueB, "Message 1");
assertFalse(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS));
}
private void fillQueue(final ActiveMQQueue queue) throws JMSException, InterruptedException {
final AtomicBoolean done = new AtomicBoolean(true);
final AtomicBoolean keepGoing = new AtomicBoolean(true);
// Starts an async thread that every time it publishes it sets the done
// flag to false.
// Once the send starts to block it will not reset the done flag
// anymore.
asyncThread = new Thread("Fill thread.") {
@Override
public void run() {
Session session = null;
try {
session = flowControlConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(queue);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
while (keepGoing.get()) {
done.set(false);
producer.send(session.createTextMessage("Hello World"));
}
} catch (JMSException e) {
} finally {
safeClose(session);
}
}
};
asyncThread.start();
waitForBlockedOrResourceLimit(done);
keepGoing.set(false);
}
protected void waitForBlockedOrResourceLimit(final AtomicBoolean done) throws InterruptedException {
while (true) {
Thread.sleep(2000);
System.out.println("check done: " + done.get() + " ex: " + gotResourceException.get());
// the producer is blocked once the done flag stays true or there is a
// resource exception
if (done.get() || gotResourceException.get()) {
break;
}
done.set(true);
}
}
private CountDownLatch asyncSendTo(final ActiveMQQueue queue, final String message) throws JMSException {
final CountDownLatch done = new CountDownLatch(1);
new Thread("Send thread.") {
@Override
public void run() {
Session session = null;
try {
session = flowControlConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(queue);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
producer.send(session.createTextMessage(message));
done.countDown();
} catch (JMSException e) {
e.printStackTrace();
} finally {
safeClose(session);
}
}
}.start();
return done;
}
@Override
protected void extraServerConfig(Configuration serverConfig) {
String match = "jms.queue.#";
Map<String, AddressSettings> asMap = serverConfig.getAddressesSettings();
asMap.get(match).setMaxSizeBytes(1).setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK);
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
this.makeSureCoreQueueExist("QUEUE.A");
this.makeSureCoreQueueExist("QUEUE.B");
}
@Override
@After
public void tearDown() throws Exception {
try {
if (flowControlConnection != null) {
TcpTransport t = flowControlConnection.getTransport().narrow(TcpTransport.class);
try {
flowControlConnection.getTransport().stop();
flowControlConnection.close();
} catch (Throwable ignored) {
// sometimes the disposed up can make the test to fail
// even worse I have seen this breaking every single test after this
// if not caught here
}
t.getTransportListener().onException(new IOException("Disposed."));
}
if (asyncThread != null) {
asyncThread.join();
asyncThread = null;
}
} finally {
super.tearDown();
}
}
}
| apache-2.0 |
ullgren/camel | components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/InlineQueryResultCachedSticker.java | 3502 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.telegram.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Represents a link to a sticker stored on the Telegram servers.
*
* @see <a href="https://core.telegram.org/bots/api#inlinequeryresultcachedsticker">
* https://core.telegram.org/bots/api#inlinequeryresultcachedsticker</a>
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class InlineQueryResultCachedSticker extends InlineQueryResult {
private static final String TYPE = "sticker";
@JsonProperty("sticker_file_id")
private String stickerFileId;
@JsonProperty("input_message_content")
private InputMessageContent inputMessageContext;
public InlineQueryResultCachedSticker() {
super(TYPE);
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String id;
private String stickerFileId;
private InlineKeyboardMarkup replyMarkup;
private InputMessageContent inputMessageContext;
private Builder() {
}
public Builder id(String id) {
this.id = id;
return this;
}
public Builder replyMarkup(InlineKeyboardMarkup replyMarkup) {
this.replyMarkup = replyMarkup;
return this;
}
public Builder stickerFileId(String stickerFileId) {
this.stickerFileId = stickerFileId;
return this;
}
public Builder inputMessageContext(InputMessageContent inputMessageContext) {
this.inputMessageContext = inputMessageContext;
return this;
}
public InlineQueryResultCachedSticker build() {
InlineQueryResultCachedSticker inlineQueryResultDocument = new InlineQueryResultCachedSticker();
inlineQueryResultDocument.setType(TYPE);
inlineQueryResultDocument.setId(id);
inlineQueryResultDocument.setReplyMarkup(replyMarkup);
inlineQueryResultDocument.inputMessageContext = this.inputMessageContext;
inlineQueryResultDocument.stickerFileId = this.stickerFileId;
return inlineQueryResultDocument;
}
}
public String getStickerFileId() {
return stickerFileId;
}
public InputMessageContent getInputMessageContext() {
return inputMessageContext;
}
public void setStickerFileId(String stickerFileId) {
this.stickerFileId = stickerFileId;
}
public void setInputMessageContext(InputMessageContent inputMessageContext) {
this.inputMessageContext = inputMessageContext;
}
}
| apache-2.0 |
gemmellr/qpid-jms | qpid-jms-client/src/test/java/org/apache/qpid/jms/message/JmsBytesMessageTest.java | 37066 | /*
* 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.qpid.jms.message;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MessageEOFException;
import javax.jms.MessageFormatException;
import javax.jms.MessageNotReadableException;
import javax.jms.MessageNotWriteableException;
import org.apache.qpid.jms.message.facade.JmsBytesMessageFacade;
import org.apache.qpid.jms.message.facade.test.JmsTestBytesMessageFacade;
import org.apache.qpid.jms.message.facade.test.JmsTestMessageFactory;
import org.junit.Test;
import org.mockito.Mockito;
/**
* Test for JMS Spec compliance for the JmsBytesMessage class using the default message facade.
*/
public class JmsBytesMessageTest {
private static final int END_OF_STREAM = -1;
private final JmsMessageFactory factory = new JmsTestMessageFactory();
@Test
public void testToString() throws Exception {
JmsBytesMessage bytesMessage = factory.createBytesMessage();
assertTrue(bytesMessage.toString().startsWith("JmsBytesMessage"));
}
/**
* Test that calling {@link BytesMessage#getBodyLength()} on a new message which has been
* populated and {@link BytesMessage#reset()} causes the length to be reported correctly.
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testResetOnNewlyPopulatedBytesMessageUpdatesBodyLength() throws Exception {
byte[] bytes = "newResetTestBytes".getBytes();
JmsBytesMessage bytesMessage = factory.createBytesMessage();
bytesMessage.writeBytes(bytes);
bytesMessage.reset();
assertEquals("Message reports unexpected length", bytes.length, bytesMessage.getBodyLength());
}
/**
* Test that attempting to call {@link BytesMessage#getBodyLength()} on a new message causes
* a {@link MessageNotReadableException} to be thrown due to being write-only.
*
* @throws Exception if an error occurs during the test.
*/
@Test(expected = MessageNotReadableException.class)
public void testGetBodyLengthOnNewMessageThrowsMessageNotReadableException() throws Exception {
JmsBytesMessage bytesMessage = factory.createBytesMessage();
bytesMessage.getBodyLength();
}
@Test
public void testReadBytesUsingReceivedMessageWithNoBodyReturnsEOS() throws Exception {
JmsBytesMessage bytesMessage = factory.createBytesMessage();
bytesMessage.onDispatch();
//verify attempting to read bytes returns -1, i.e EOS
assertEquals("Expected input stream to be at end but data was returned", END_OF_STREAM, bytesMessage.readBytes(new byte[1]));
}
@Test
public void testReadBytesUsingReceivedMessageWithBodyReturnsBytes() throws Exception {
byte[] content = "myBytesData".getBytes();
JmsTestBytesMessageFacade facade = new JmsTestBytesMessageFacade(content);
JmsBytesMessage bytesMessage = new JmsBytesMessage(facade);
bytesMessage.onDispatch();
// retrieve the expected bytes, check they match
byte[] receivedBytes = new byte[content.length];
bytesMessage.readBytes(receivedBytes);
assertTrue(Arrays.equals(content, receivedBytes));
// verify no more bytes remain, i.e EOS
assertEquals("Expected input stream to be at end but data was returned",
END_OF_STREAM, bytesMessage.readBytes(new byte[1]));
assertEquals("Message reports unexpected length", content.length, bytesMessage.getBodyLength());
}
/**
* Test that attempting to write bytes to a received message (without calling {@link BytesMessage#clearBody()} first)
* causes a {@link MessageNotWriteableException} to be thrown due to being read-only.
*
* @throws Exception if an error occurs during the test.
*/
@Test(expected = MessageNotWriteableException.class)
public void testReceivedBytesMessageThrowsMessageNotWriteableExceptionOnWriteBytes() throws Exception {
byte[] content = "myBytesData".getBytes();
JmsTestBytesMessageFacade facade = new JmsTestBytesMessageFacade(content);
JmsBytesMessage bytesMessage = new JmsBytesMessage(facade);
bytesMessage.onDispatch();
bytesMessage.writeBytes(content);
}
/**
* Test that attempting to read bytes from a new message (without calling {@link BytesMessage#reset()} first) causes a
* {@link MessageNotReadableException} to be thrown due to being write-only.
*
* @throws Exception if an error occurs during the test.
*/
@Test(expected = MessageNotReadableException.class)
public void testNewBytesMessageThrowsMessageNotReadableOnReadBytes() throws Exception {
JmsBytesMessage bytesMessage = factory.createBytesMessage();
byte[] receivedBytes = new byte[1];
bytesMessage.readBytes(receivedBytes);
}
/**
* Test that calling {@link BytesMessage#clearBody()} causes a received
* message to become writable
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testClearBodyOnReceivedBytesMessageMakesMessageWritable() throws Exception {
byte[] content = "myBytesData".getBytes();
JmsTestBytesMessageFacade facade = new JmsTestBytesMessageFacade(content);
JmsBytesMessage bytesMessage = new JmsBytesMessage(facade);
bytesMessage.onDispatch();
assertTrue("Message should not be writable", bytesMessage.isReadOnlyBody());
bytesMessage.clearBody();
assertFalse("Message should be writable", bytesMessage.isReadOnlyBody());
}
/**
* Test that calling {@link BytesMessage#clearBody()} of a received message
* causes the facade input stream to be empty and body length to return 0.
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testClearBodyOnReceivedBytesMessageClearsFacadeInputStream() throws Exception {
byte[] content = "myBytesData".getBytes();
JmsTestBytesMessageFacade facade = new JmsTestBytesMessageFacade(content);
JmsBytesMessage bytesMessage = new JmsBytesMessage(facade);
bytesMessage.onDispatch();
assertTrue("Expected message content but none was present", facade.getBodyLength() > 0);
assertEquals("Expected data from facade", 1, facade.getInputStream().read(new byte[1]));
bytesMessage.clearBody();
assertTrue("Expected no message content from facade", facade.getBodyLength() == 0);
assertEquals("Expected no data from facade, but got some", END_OF_STREAM, facade.getInputStream().read(new byte[1]));
}
/**
* Test that attempting to call {@link BytesMessage#getBodyLength()} on a received message after calling
* {@link BytesMessage#clearBody()} causes {@link MessageNotReadableException} to be thrown due to being write-only.
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testGetBodyLengthOnClearedReceivedMessageThrowsMessageNotReadableException() throws Exception {
byte[] content = "myBytesData".getBytes();
JmsTestBytesMessageFacade facade = new JmsTestBytesMessageFacade(content);
JmsBytesMessage bytesMessage = new JmsBytesMessage(facade);
bytesMessage.onDispatch();
assertEquals("Unexpected message length", content.length, bytesMessage.getBodyLength());
bytesMessage.clearBody();
try {
bytesMessage.getBodyLength();
fail("expected exception to be thrown");
} catch (MessageNotReadableException mnre) {
// expected
}
}
/**
* Test that calling {@link BytesMessage#reset()} causes a write-only
* message to become read-only
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testResetOnReceivedBytesMessageResetsMarker() throws Exception {
byte[] content = "myBytesData".getBytes();
JmsTestBytesMessageFacade facade = new JmsTestBytesMessageFacade(content);
JmsBytesMessage bytesMessage = new JmsBytesMessage(facade);
bytesMessage.onDispatch();
// retrieve a few bytes, check they match the first few expected bytes
byte[] partialBytes = new byte[3];
bytesMessage.readBytes(partialBytes);
byte[] partialOriginalBytes = Arrays.copyOf(content, 3);
assertTrue(Arrays.equals(partialOriginalBytes, partialBytes));
bytesMessage.reset();
// retrieve all the expected bytes, check they match
byte[] resetBytes = new byte[content.length];
bytesMessage.readBytes(resetBytes);
assertTrue(Arrays.equals(content, resetBytes));
}
/**
* Test that calling {@link BytesMessage#reset()} on a new message which has been populated
* causes the marker to be reset and makes the message read-only
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testResetOnNewlyPopulatedBytesMessageResetsMarkerAndMakesReadable() throws Exception {
byte[] content = "myBytesData".getBytes();
JmsTestBytesMessageFacade facade = new JmsTestBytesMessageFacade(content);
JmsBytesMessage bytesMessage = new JmsBytesMessage(facade);
assertFalse("Message should be writable", bytesMessage.isReadOnlyBody());
bytesMessage.writeBytes(content);
bytesMessage.reset();
assertTrue("Message should not be writable", bytesMessage.isReadOnlyBody());
// retrieve the bytes, check they match
byte[] resetBytes = new byte[content.length];
bytesMessage.readBytes(resetBytes);
assertTrue(Arrays.equals(content, resetBytes));
}
/**
* Verify that nothing is read when {@link BytesMessage#readBytes(byte[])} is
* called with a zero length destination array.
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testReadBytesWithZeroLengthDestination() throws Exception {
JmsBytesMessage bytesMessage = factory.createBytesMessage();
bytesMessage.reset();
assertEquals("Did not expect any bytes to be read", 0, bytesMessage.readBytes(new byte[0]));
}
/**
* Verify that when {@link BytesMessage#readBytes(byte[], int)} is called
* with a negative length that an {@link IndexOutOfBoundsException} is thrown.
*
* @throws Exception if an error occurs during the test.
*/
@Test(expected=IndexOutOfBoundsException.class)
public void testReadBytesWithNegativeLengthThrowsIOOBE() throws Exception
{
JmsBytesMessage bytesMessage = factory.createBytesMessage();
bytesMessage.reset();
bytesMessage.readBytes(new byte[0], -1);
}
/**
* Verify that when {@link BytesMessage#readBytes(byte[], int)} is called
* with a length that is greater than the size of the provided array,
* an {@link IndexOutOfBoundsException} is thrown.
*
* @throws Exception if an error occurs during the test.
*/
@Test(expected=IndexOutOfBoundsException.class)
public void testReadBytesWithLengthGreatThanArraySizeThrowsIOOBE() throws Exception {
JmsBytesMessage bytesMessage = factory.createBytesMessage();
bytesMessage.reset();
bytesMessage.readBytes(new byte[1], 2);
}
/**
* Test that writing a null using {@link BytesMessage#writeObject(Object)}
* results in a NPE being thrown.
*
* @throws Exception if an error occurs during the test.
*/
@Test(expected=NullPointerException.class)
public void testWriteObjectWithNullThrowsNPE() throws Exception {
JmsBytesMessage bytesMessage = factory.createBytesMessage();
bytesMessage.writeObject(null);
}
/**
* Test that writing a null using {@link BytesMessage#writeObject(Object)}
* results in an {@link MessageFormatException} being thrown.
*
* @throws Exception if an error occurs during the test.
*/
@Test(expected=MessageFormatException.class)
public void testWriteObjectWithIllegalTypeThrowsMFE() throws Exception {
JmsBytesMessage bytesMessage = factory.createBytesMessage();
bytesMessage.writeObject(new Object());
}
@Test
public void testGetBodyLength() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
int len = 10;
for (int i = 0; i < len; i++) {
msg.writeLong(5L);
}
msg.reset();
assertTrue(msg.getBodyLength() == (len * 8));
}
@Test
public void testReadBoolean() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
msg.writeBoolean(true);
msg.reset();
assertTrue(msg.readBoolean());
}
@Test
public void testReadByte() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
msg.writeByte((byte) 2);
msg.reset();
assertTrue(msg.readByte() == 2);
}
@Test
public void testReadUnsignedByte() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
msg.writeByte((byte) 2);
msg.reset();
assertTrue(msg.readUnsignedByte() == 2);
}
@Test
public void testReadShort() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
msg.writeShort((short) 3000);
msg.reset();
assertTrue(msg.readShort() == 3000);
}
@Test
public void testReadUnsignedShort() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
msg.writeShort((short) 3000);
msg.reset();
assertTrue(msg.readUnsignedShort() == 3000);
}
@Test
public void testReadChar() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
msg.writeChar('a');
msg.reset();
assertTrue(msg.readChar() == 'a');
}
@Test
public void testReadInt() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
msg.writeInt(3000);
msg.reset();
assertTrue(msg.readInt() == 3000);
}
@Test
public void testReadLong() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
msg.writeLong(3000);
msg.reset();
assertTrue(msg.readLong() == 3000);
}
@Test
public void testReadFloat() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
msg.writeFloat(3.3f);
msg.reset();
assertTrue(msg.readFloat() == 3.3f);
}
@Test
public void testReadDouble() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
msg.writeDouble(3.3d);
msg.reset();
assertTrue(msg.readDouble() == 3.3d);
}
@Test
public void testReadUTF() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
String str = "this is a test";
msg.writeUTF(str);
msg.reset();
assertTrue(msg.readUTF().equals(str));
}
@Test
public void testReadBytesbyteArray() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
byte[] data = new byte[50];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) i;
}
msg.writeBytes(data);
msg.reset();
byte[] test = new byte[data.length];
msg.readBytes(test);
for (int i = 0; i < test.length; i++) {
assertTrue(test[i] == i);
}
}
@Test
public void testWriteObject() throws JMSException {
JmsBytesMessage msg = factory.createBytesMessage();
try {
msg.writeObject("fred");
msg.writeObject(Boolean.TRUE);
msg.writeObject(Character.valueOf('q'));
msg.writeObject(Byte.valueOf((byte) 1));
msg.writeObject(Short.valueOf((short) 3));
msg.writeObject(Integer.valueOf(3));
msg.writeObject(Long.valueOf(300L));
msg.writeObject(Float.valueOf(3.3f));
msg.writeObject(Double.valueOf(3.3));
msg.writeObject(new byte[3]);
} catch (MessageFormatException mfe) {
fail("objectified primitives should be allowed");
}
try {
msg.writeObject(new Object());
fail("only objectified primitives are allowed");
} catch (MessageFormatException mfe) {
}
}
@Test
public void testClearBodyOnNewMessage() throws JMSException {
JmsBytesMessage bytesMessage = factory.createBytesMessage();
bytesMessage.writeInt(1);
bytesMessage.clearBody();
assertFalse(bytesMessage.isReadOnlyBody());
bytesMessage.reset();
assertEquals(0, bytesMessage.getBodyLength());
}
@Test
public void testReset() throws JMSException {
JmsBytesMessage message = factory.createBytesMessage();
try {
message.writeDouble(24.5);
message.writeLong(311);
} catch (MessageNotWriteableException mnwe) {
fail("should be writeable");
}
message.reset();
try {
assertTrue(message.isReadOnlyBody());
assertEquals(message.readDouble(), 24.5, 0);
assertEquals(message.readLong(), 311);
} catch (MessageNotReadableException mnre) {
fail("should be readable");
}
try {
message.writeInt(33);
fail("should throw exception");
} catch (MessageNotWriteableException mnwe) {
}
}
@Test
public void testReadOnlyBody() throws JMSException {
JmsBytesMessage message = factory.createBytesMessage();
try {
message.writeBoolean(true);
message.writeByte((byte) 1);
message.writeByte((byte) 1);
message.writeBytes(new byte[1]);
message.writeBytes(new byte[3], 0, 2);
message.writeChar('a');
message.writeDouble(1.5);
message.writeFloat((float) 1.5);
message.writeInt(1);
message.writeLong(1);
message.writeObject("stringobj");
message.writeShort((short) 1);
message.writeShort((short) 1);
message.writeUTF("utfstring");
} catch (MessageNotWriteableException mnwe) {
fail("Should be writeable");
}
message.reset();
try {
message.readBoolean();
message.readByte();
message.readUnsignedByte();
message.readBytes(new byte[1]);
message.readBytes(new byte[2], 2);
message.readChar();
message.readDouble();
message.readFloat();
message.readInt();
message.readLong();
message.readUTF();
message.readShort();
message.readUnsignedShort();
message.readUTF();
} catch (MessageNotReadableException mnwe) {
fail("Should be readable");
}
try {
message.writeBoolean(true);
fail("Should have thrown exception");
} catch (MessageNotWriteableException mnwe) {
}
try {
message.writeByte((byte) 1);
fail("Should have thrown exception");
} catch (MessageNotWriteableException mnwe) {
}
try {
message.writeBytes(new byte[1]);
fail("Should have thrown exception");
} catch (MessageNotWriteableException mnwe) {
}
try {
message.writeBytes(new byte[3], 0, 2);
fail("Should have thrown exception");
} catch (MessageNotWriteableException mnwe) {
}
try {
message.writeChar('a');
fail("Should have thrown exception");
} catch (MessageNotWriteableException mnwe) {
}
try {
message.writeDouble(1.5);
fail("Should have thrown exception");
} catch (MessageNotWriteableException mnwe) {
}
try {
message.writeFloat((float) 1.5);
fail("Should have thrown exception");
} catch (MessageNotWriteableException mnwe) {
}
try {
message.writeInt(1);
fail("Should have thrown exception");
} catch (MessageNotWriteableException mnwe) {
}
try {
message.writeLong(1);
fail("Should have thrown exception");
} catch (MessageNotWriteableException mnwe) {
}
try {
message.writeObject("stringobj");
fail("Should have thrown exception");
} catch (MessageNotWriteableException mnwe) {
}
try {
message.writeShort((short) 1);
fail("Should have thrown exception");
} catch (MessageNotWriteableException mnwe) {
}
try {
message.writeUTF("utfstring");
fail("Should have thrown exception");
} catch (MessageNotWriteableException mnwe) {
}
}
@Test
public void testWriteOnlyBody() throws JMSException {
JmsBytesMessage message = factory.createBytesMessage();
message.clearBody();
try {
message.writeBoolean(true);
message.writeByte((byte) 1);
message.writeByte((byte) 1);
message.writeBytes(new byte[1]);
message.writeBytes(new byte[3], 0, 2);
message.writeChar('a');
message.writeDouble(1.5);
message.writeFloat((float) 1.5);
message.writeInt(1);
message.writeLong(1);
message.writeObject("stringobj");
message.writeShort((short) 1);
message.writeShort((short) 1);
message.writeUTF("utfstring");
} catch (MessageNotWriteableException mnwe) {
fail("Should be writeable");
}
try {
message.readBoolean();
fail("Should have thrown exception");
} catch (MessageNotReadableException mnwe) {
}
try {
message.readByte();
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
try {
message.readUnsignedByte();
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
try {
message.readBytes(new byte[1]);
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
try {
message.readBytes(new byte[2], 2);
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
try {
message.readChar();
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
try {
message.readDouble();
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
try {
message.readFloat();
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
try {
message.readInt();
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
try {
message.readLong();
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
try {
message.readUTF();
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
try {
message.readShort();
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
try {
message.readUnsignedShort();
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
try {
message.readUTF();
fail("Should have thrown exception");
} catch (MessageNotReadableException e) {
}
}
//---------- Test that errors are trapped correctly ----------------------//
@Test
public void testReadMethodsCaptureEOFExceptionThrowsMessageEOFEx() throws Exception {
JmsBytesMessageFacade facade = Mockito.mock(JmsBytesMessageFacade.class);
InputStream bytesIn = Mockito.mock(InputStream.class);
Mockito.when(facade.getInputStream()).thenReturn(bytesIn);
Mockito.when(bytesIn.read()).thenThrow(new EOFException());
Mockito.when(bytesIn.read(Mockito.any(byte[].class))).thenThrow(new EOFException());
Mockito.when(bytesIn.read(Mockito.any(byte[].class), Mockito.anyInt(), Mockito.anyInt())).thenThrow(new EOFException());
JmsBytesMessage message = new JmsBytesMessage(facade);
message.reset();
try {
message.readBoolean();
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
try {
message.readByte();
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
try {
message.readBytes(new byte[10]);
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
try {
message.readBytes(new byte[10], 10);
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
try {
message.readChar();
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
try {
message.readDouble();
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
try {
message.readFloat();
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
try {
message.readInt();
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
try {
message.readLong();
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
try {
message.readShort();
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
try {
message.readUnsignedByte();
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
try {
message.readUnsignedShort();
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
try {
message.readUTF();
} catch (MessageEOFException ex) {
assertTrue(ex.getCause() instanceof EOFException);
}
}
@Test
public void testReadMethodsCaptureIOExceptionThrowsJMSEx() throws Exception {
JmsBytesMessageFacade facade = Mockito.mock(JmsBytesMessageFacade.class);
InputStream bytesIn = Mockito.mock(InputStream.class);
Mockito.when(facade.getInputStream()).thenReturn(bytesIn);
Mockito.when(bytesIn.read()).thenThrow(new IOException());
Mockito.when(bytesIn.read(Mockito.any(byte[].class))).thenThrow(new IOException());
Mockito.when(bytesIn.read(Mockito.any(byte[].class), Mockito.anyInt(), Mockito.anyInt())).thenThrow(new IOException());
JmsBytesMessage message = new JmsBytesMessage(facade);
message.reset();
try {
message.readBoolean();
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.readByte();
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.readBytes(new byte[10]);
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.readBytes(new byte[10], 10);
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.readChar();
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.readDouble();
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.readFloat();
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.readInt();
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.readLong();
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.readShort();
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.readUnsignedByte();
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.readUnsignedShort();
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.readUTF();
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
}
@Test
public void testWriteMethodsCaptureIOExceptionThrowsJMSEx() throws Exception {
JmsBytesMessageFacade facade = Mockito.mock(JmsBytesMessageFacade.class);
OutputStream bytesOut = Mockito.mock(OutputStream.class);
Mockito.when(facade.getOutputStream()).thenReturn(bytesOut);
Mockito.doThrow(new IOException()).when(bytesOut).write(Mockito.anyByte());
Mockito.doThrow(new IOException()).when(bytesOut).write(Mockito.any(byte[].class));
Mockito.doThrow(new IOException()).when(bytesOut).write(Mockito.any(byte[].class), Mockito.anyInt(), Mockito.anyInt());
JmsBytesMessage message = new JmsBytesMessage(facade);
try {
message.writeBoolean(false);
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.writeByte((byte) 128);
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.writeBytes(new byte[10]);
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.writeBytes(new byte[10], 0, 10);
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.writeChar('a');
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.writeDouble(100.0);
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.writeFloat(10.2f);
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.writeInt(125);
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.writeLong(65536L);
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.writeObject("");
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.writeShort((short) 32768);
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
try {
message.writeUTF("");
} catch (JMSException ex) {
assertTrue(ex.getCause() instanceof IOException);
}
}
@Test
public void testGetBodyThrowsMessageFormatException() throws JMSException {
JmsBytesMessage bytesMessage = factory.createBytesMessage();
bytesMessage.setStringProperty("property", "value");
bytesMessage.writeByte((byte) 1);
bytesMessage.writeInt(22);
try {
bytesMessage.getBody(StringBuffer.class);
fail("should have thrown MessageFormatException");
} catch (MessageFormatException mfe) {
} catch (Exception e) {
fail("should have thrown MessageFormatException");
}
try {
bytesMessage.getBody(String.class);
fail("should have thrown MessageFormatException");
} catch (MessageFormatException mfe) {
} catch (Exception e) {
fail("should have thrown MessageFormatException");
}
try {
bytesMessage.getBody(Map.class);
fail("should have thrown MessageFormatException");
} catch (MessageFormatException mfe) {
} catch (Exception e) {
fail("should have thrown MessageFormatException");
}
try {
bytesMessage.getBody(List.class);
fail("should have thrown MessageFormatException");
} catch (MessageFormatException mfe) {
} catch (Exception e) {
fail("should have thrown MessageFormatException");
}
try {
bytesMessage.getBody(Array.class);
fail("should have thrown MessageFormatException");
} catch (MessageFormatException mfe) {
} catch (Exception e) {
fail("should have thrown MessageFormatException");
}
byte[] read1 = bytesMessage.getBody(byte[].class);
assertNotNull(read1);
byte[] read2 = (byte[]) bytesMessage.getBody(Object.class);
assertNotNull(read2);
}
//---------- Test for misc message methods -------------------------------//
@Test
public void testHashCode() throws Exception {
String messageId = "ID:SOME-ID:0:1:1";
JmsBytesMessage message = factory.createBytesMessage();
message.setJMSMessageID(messageId);
assertEquals(message.getJMSMessageID().hashCode(), messageId.hashCode());
assertEquals(message.hashCode(), messageId.hashCode());
}
@Test
public void testEqualsObject() throws Exception {
String messageId = "ID:SOME-ID:0:1:1";
JmsBytesMessage message1 = factory.createBytesMessage();
JmsBytesMessage message2 = factory.createBytesMessage();
message1.setJMSMessageID(messageId);
assertTrue(!message1.equals(message2));
assertTrue(!message2.equals(message1));
message2.setJMSMessageID(messageId);
assertTrue(message1.equals(message2));
assertTrue(message2.equals(message1));
message2.setJMSMessageID(messageId + "More");
assertTrue(!message1.equals(message2));
assertTrue(!message2.equals(message1));
assertTrue(message1.equals(message1));
assertFalse(message1.equals(null));
assertFalse(message1.equals(""));
}
}
| apache-2.0 |
arunasujith/msf4j | core/src/main/java/org/wso2/msf4j/HttpStreamHandler.java | 1715 | /*
* Copyright (c) 2016, WSO2 Inc. (http://wso2.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 org.wso2.msf4j;
import java.nio.ByteBuffer;
/**
* HttpHandler would extend this abstract class and implement methods to stream the body directly.
* chunk method would receive the http-chunks of the body and finished would be called
* on receipt of the last chunk.
*/
public interface HttpStreamHandler {
/**
* Initialize the stream handler.
*
* @param response response object that should be used to send response
*/
void init(Response response);
/**
* Http request content will be streamed directly to this method.
*
* @param content content of chunks
*/
void chunk(ByteBuffer content) throws Exception;
/**
* This method will be called when all chunks
* have been completely streamed.
*
* @throws Exception
*/
void end() throws Exception;
/**
* When there is exception on netty while streaming, it will be propagated to handler
* so the handler can do the cleanup.
*
* @param cause Cause of the Exception
*/
void error(Throwable cause);
}
| apache-2.0 |
treasure-data/presto | presto-orc/src/main/java/io/prestosql/orc/metadata/statistics/Utf8BloomFilterBuilder.java | 1522 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.orc.metadata.statistics;
import io.airlift.slice.Slice;
public class Utf8BloomFilterBuilder
implements BloomFilterBuilder
{
private final BloomFilter bloomFilter;
public Utf8BloomFilterBuilder(int expectedSize, double fpp)
{
bloomFilter = new BloomFilter(expectedSize, fpp);
}
@Override
public BloomFilterBuilder addString(Slice val)
{
bloomFilter.add(val);
return this;
}
@Override
public BloomFilterBuilder addLong(long val)
{
bloomFilter.addLong(val);
return this;
}
@Override
public BloomFilterBuilder addDouble(double val)
{
bloomFilter.addDouble(val);
return this;
}
@Override
public BloomFilterBuilder addFloat(float val)
{
bloomFilter.addFloat(val);
return this;
}
@Override
public BloomFilter buildBloomFilter()
{
return bloomFilter;
}
}
| apache-2.0 |
falko/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/pvm/delegate/SignallableActivityBehavior.java | 1067 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.engine.impl.pvm.delegate;
/**
* @author Tom Baeyens
*/
public interface SignallableActivityBehavior extends ActivityBehavior {
void signal(ActivityExecution execution, String signalEvent, Object signalData) throws Exception;
}
| apache-2.0 |
tzulitai/flink | flink-yarn-tests/src/test/java/org/apache/flink/yarn/YarnTestBase.java | 38762 | /*
* 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.flink.yarn;
import org.apache.flink.api.common.time.Deadline;
import org.apache.flink.client.cli.CliFrontend;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.GlobalConfiguration;
import org.apache.flink.runtime.clusterframework.BootstrapTools;
import org.apache.flink.test.util.TestBaseUtils;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.TestLogger;
import org.apache.flink.util.function.RunnableWithException;
import org.apache.flink.yarn.cli.FlinkYarnSessionCli;
import org.apache.flink.yarn.util.TestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.service.Service;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.client.api.YarnClient;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.server.MiniYARNCluster;
import org.apache.hadoop.yarn.server.nodemanager.NodeManager;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.apache.flink.util.Preconditions.checkState;
import static org.junit.Assert.assertEquals;
/**
* This base class allows to use the MiniYARNCluster.
* The cluster is re-used for all tests.
*
* <p>This class is located in a different package which is build after flink-dist. This way,
* we can use the YARN uberjar of flink to start a Flink YARN session.
*
* <p>The test is not thread-safe. Parallel execution of tests is not possible!
*/
public abstract class YarnTestBase extends TestLogger {
private static final Logger LOG = LoggerFactory.getLogger(YarnTestBase.class);
protected static final PrintStream ORIGINAL_STDOUT = System.out;
protected static final PrintStream ORIGINAL_STDERR = System.err;
private static final InputStream ORIGINAL_STDIN = System.in;
protected static final String TEST_CLUSTER_NAME_KEY = "flink-yarn-minicluster-name";
protected static final int NUM_NODEMANAGERS = 2;
/** The tests are scanning for these strings in the final output. */
protected static final String[] PROHIBITED_STRINGS = {
"Exception", // we don't want any exceptions to happen
"Started SelectChannelConnector@0.0.0.0:8081" // Jetty should start on a random port in YARN mode.
};
/** These strings are white-listed, overriding the prohibited strings. */
protected static final String[] WHITELISTED_STRINGS = {
"akka.remote.RemoteTransportExceptionNoStackTrace",
// workaround for annoying InterruptedException logging:
// https://issues.apache.org/jira/browse/YARN-1022
"java.lang.InterruptedException",
// very specific on purpose
"Remote connection to [null] failed with java.net.ConnectException: Connection refused",
"Remote connection to [null] failed with java.nio.channels.NotYetConnectedException",
"java.io.IOException: Connection reset by peer",
// filter out expected ResourceManagerException caused by intended shutdown request
YarnResourceManager.ERROR_MASSAGE_ON_SHUTDOWN_REQUEST,
// this can happen in Akka 2.4 on shutdown.
"java.util.concurrent.RejectedExecutionException: Worker has already been shutdown",
"org.apache.flink.util.FlinkException: Stopping JobMaster",
"org.apache.flink.util.FlinkException: JobManager is shutting down.",
"lost the leadership."
};
// Temp directory which is deleted after the unit test.
@ClassRule
public static TemporaryFolder tmp = new TemporaryFolder();
// Temp directory for mini hdfs
@ClassRule
public static TemporaryFolder tmpHDFS = new TemporaryFolder();
protected static MiniYARNCluster yarnCluster = null;
protected static MiniDFSCluster miniDFSCluster = null;
/**
* Uberjar (fat jar) file of Flink.
*/
protected static File flinkUberjar;
protected static final YarnConfiguration YARN_CONFIGURATION;
/**
* lib/ folder of the flink distribution.
*/
protected static File flinkLibFolder;
/**
* Temporary folder where Flink configurations will be kept for secure run.
*/
protected static File tempConfPathForSecureRun = null;
protected static File yarnSiteXML = null;
protected static File hdfsSiteXML = null;
private YarnClient yarnClient = null;
private static org.apache.flink.configuration.Configuration globalConfiguration;
protected org.apache.flink.configuration.Configuration flinkConfiguration;
static {
YARN_CONFIGURATION = new YarnConfiguration();
YARN_CONFIGURATION.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 32);
YARN_CONFIGURATION.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, 4096); // 4096 is the available memory anyways
YARN_CONFIGURATION.setBoolean(YarnConfiguration.RM_SCHEDULER_INCLUDE_PORT_IN_NODE_NAME, true);
YARN_CONFIGURATION.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 2);
YARN_CONFIGURATION.setInt(YarnConfiguration.RM_MAX_COMPLETED_APPLICATIONS, 2);
YARN_CONFIGURATION.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, 4);
YARN_CONFIGURATION.setInt(YarnConfiguration.DEBUG_NM_DELETE_DELAY_SEC, 3600);
YARN_CONFIGURATION.setBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, false);
YARN_CONFIGURATION.setInt(YarnConfiguration.NM_VCORES, 666); // memory is overwritten in the MiniYARNCluster.
// so we have to change the number of cores for testing.
YARN_CONFIGURATION.setInt(YarnConfiguration.RM_AM_EXPIRY_INTERVAL_MS, 20000); // 20 seconds expiry (to ensure we properly heartbeat with YARN).
YARN_CONFIGURATION.setFloat(YarnConfiguration.NM_MAX_PER_DISK_UTILIZATION_PERCENTAGE, 99.0F);
YARN_CONFIGURATION.set(YarnConfiguration.YARN_APPLICATION_CLASSPATH, getYarnClasspath());
}
/**
* Searches for the yarn.classpath file generated by the "dependency:build-classpath" maven plugin in
* "flink-yarn-tests".
* @return a classpath suitable for running all YARN-launched JVMs
*/
private static String getYarnClasspath() {
final String start = "../flink-yarn-tests";
try {
File classPathFile = TestUtils.findFile(start, (dir, name) -> name.equals("yarn.classpath"));
return FileUtils.readFileToString(classPathFile); // potential NPE is supposed to be fatal
} catch (Throwable t) {
LOG.error("Error while getting YARN classpath in {}", new File(start).getAbsoluteFile(), t);
throw new RuntimeException("Error while getting YARN classpath", t);
}
}
public static void populateYarnSecureConfigurations(Configuration conf, String principal, String keytab) {
conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, "true");
conf.set(YarnConfiguration.RM_KEYTAB, keytab);
conf.set(YarnConfiguration.RM_PRINCIPAL, principal);
conf.set(YarnConfiguration.NM_KEYTAB, keytab);
conf.set(YarnConfiguration.NM_PRINCIPAL, principal);
conf.set(YarnConfiguration.RM_WEBAPP_SPNEGO_USER_NAME_KEY, principal);
conf.set(YarnConfiguration.RM_WEBAPP_SPNEGO_KEYTAB_FILE_KEY, keytab);
conf.set(YarnConfiguration.NM_WEBAPP_SPNEGO_USER_NAME_KEY, principal);
conf.set(YarnConfiguration.NM_WEBAPP_SPNEGO_KEYTAB_FILE_KEY, keytab);
conf.set("hadoop.security.auth_to_local", "RULE:[1:$1] RULE:[2:$1]");
}
@Before
public void setupYarnClient() {
if (yarnClient == null) {
yarnClient = YarnClient.createYarnClient();
yarnClient.init(getYarnConfiguration());
yarnClient.start();
}
flinkConfiguration = new org.apache.flink.configuration.Configuration(globalConfiguration);
}
/**
* Sleep a bit between the tests (we are re-using the YARN cluster for the tests).
*/
@After
public void shutdownYarnClient() {
yarnClient.stop();
}
protected void runTest(RunnableWithException test) throws Exception {
// wrapping the cleanup logic in an AutoClosable automatically suppresses additional exceptions
try (final CleanupYarnApplication ignored = new CleanupYarnApplication()) {
test.run();
}
}
private class CleanupYarnApplication implements AutoCloseable {
@Override
public void close() throws Exception {
Deadline deadline = Deadline.now().plus(Duration.ofSeconds(10));
boolean isAnyJobRunning = yarnClient.getApplications().stream()
.anyMatch(YarnTestBase::isApplicationRunning);
while (deadline.hasTimeLeft() && isAnyJobRunning) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Assert.fail("Should not happen");
}
isAnyJobRunning = yarnClient.getApplications().stream()
.anyMatch(YarnTestBase::isApplicationRunning);
}
if (isAnyJobRunning) {
final List<String> runningApps = yarnClient.getApplications().stream()
.filter(YarnTestBase::isApplicationRunning)
.map(app -> "App " + app.getApplicationId() + " is in state " + app.getYarnApplicationState() + '.')
.collect(Collectors.toList());
if (!runningApps.isEmpty()) {
Assert.fail("There is at least one application on the cluster that is not finished." + runningApps);
}
}
}
}
private static boolean isApplicationRunning(ApplicationReport app) {
final YarnApplicationState yarnApplicationState = app.getYarnApplicationState();
return yarnApplicationState != YarnApplicationState.FINISHED
&& app.getYarnApplicationState() != YarnApplicationState.KILLED
&& app.getYarnApplicationState() != YarnApplicationState.FAILED;
}
@Nullable
protected YarnClient getYarnClient() {
return yarnClient;
}
protected static YarnConfiguration getYarnConfiguration() {
return YARN_CONFIGURATION;
}
@Nonnull
YarnClusterDescriptor createYarnClusterDescriptor(org.apache.flink.configuration.Configuration flinkConfiguration) {
final YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptorWithoutLibDir(flinkConfiguration);
yarnClusterDescriptor.addShipFiles(Collections.singletonList(flinkLibFolder));
return yarnClusterDescriptor;
}
YarnClusterDescriptor createYarnClusterDescriptorWithoutLibDir(org.apache.flink.configuration.Configuration flinkConfiguration) {
final YarnClusterDescriptor yarnClusterDescriptor = YarnTestUtils.createClusterDescriptorWithLogging(
tempConfPathForSecureRun.getAbsolutePath(),
flinkConfiguration,
YARN_CONFIGURATION,
yarnClient,
true);
yarnClusterDescriptor.setLocalJarPath(new Path(flinkUberjar.toURI()));
return yarnClusterDescriptor;
}
/**
* A simple {@link FilenameFilter} that only accepts files if their name contains every string in the array passed
* to the constructor.
*/
public static class ContainsName implements FilenameFilter {
private String[] names;
private String excludeInPath = null;
/**
* @param names which have to be included in the filename.
*/
public ContainsName(String[] names) {
this.names = names;
}
public ContainsName(String[] names, String excludeInPath) {
this.names = names;
this.excludeInPath = excludeInPath;
}
@Override
public boolean accept(File dir, String name) {
if (excludeInPath == null) {
for (String n: names) {
if (!name.contains(n)) {
return false;
}
}
return true;
} else {
for (String n: names) {
if (!name.contains(n)) {
return false;
}
}
return !dir.toString().contains(excludeInPath);
}
}
}
// write yarn-site.xml to target/test-classes so that flink pick can pick up this when
// initializing YarnClient properly from classpath
public static void writeYarnSiteConfigXML(Configuration yarnConf, File targetFolder) throws IOException {
yarnSiteXML = new File(targetFolder, "/yarn-site.xml");
try (FileWriter writer = new FileWriter(yarnSiteXML)) {
yarnConf.writeXml(writer);
writer.flush();
}
}
private static void writeHDFSSiteConfigXML(Configuration coreSite, File targetFolder) throws IOException {
hdfsSiteXML = new File(targetFolder, "/hdfs-site.xml");
try (FileWriter writer = new FileWriter(hdfsSiteXML)) {
coreSite.writeXml(writer);
writer.flush();
}
}
/**
* This method checks the written TaskManager and JobManager log files
* for exceptions.
*
* <p>WARN: Please make sure the tool doesn't find old logfiles from previous test runs.
* So always run "mvn clean" before running the tests here.
*
*/
public static void ensureNoProhibitedStringInLogFiles(final String[] prohibited, final String[] whitelisted) {
File cwd = new File("target/" + YARN_CONFIGURATION.get(TEST_CLUSTER_NAME_KEY));
Assert.assertTrue("Expecting directory " + cwd.getAbsolutePath() + " to exist", cwd.exists());
Assert.assertTrue("Expecting directory " + cwd.getAbsolutePath() + " to be a directory", cwd.isDirectory());
List<String> prohibitedExcerpts = new ArrayList<>();
File foundFile = TestUtils.findFile(cwd.getAbsolutePath(), new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// scan each file for prohibited strings.
File f = new File(dir.getAbsolutePath() + "/" + name);
try {
BufferingScanner scanner = new BufferingScanner(new Scanner(f), 10);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
for (String aProhibited : prohibited) {
if (lineFromFile.contains(aProhibited)) {
boolean whitelistedFound = false;
for (String white : whitelisted) {
if (lineFromFile.contains(white)) {
whitelistedFound = true;
break;
}
}
if (!whitelistedFound) {
// logging in FATAL to see the actual message in CI tests.
Marker fatal = MarkerFactory.getMarker("FATAL");
LOG.error(fatal, "Prohibited String '{}' in '{}:{}'", aProhibited, f.getAbsolutePath(), lineFromFile);
StringBuilder logExcerpt = new StringBuilder();
logExcerpt.append(System.lineSeparator());
// include some previous lines in case of irregular formatting
for (String previousLine : scanner.getPreviousLines()) {
logExcerpt.append(previousLine);
logExcerpt.append(System.lineSeparator());
}
logExcerpt.append(lineFromFile);
logExcerpt.append(System.lineSeparator());
// extract potential stack trace from log
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
logExcerpt.append(line);
logExcerpt.append(System.lineSeparator());
if (line.isEmpty() || (!Character.isWhitespace(line.charAt(0)) && !line.startsWith("Caused by"))) {
// the cause has been printed, now add a few more lines in case of irregular formatting
for (int x = 0; x < 10 && scanner.hasNextLine(); x++) {
logExcerpt.append(scanner.nextLine());
logExcerpt.append(System.lineSeparator());
}
break;
}
}
prohibitedExcerpts.add(logExcerpt.toString());
return true;
}
}
}
}
} catch (FileNotFoundException e) {
LOG.warn("Unable to locate file: " + e.getMessage() + " file: " + f.getAbsolutePath());
}
return false;
}
});
if (foundFile != null) {
Scanner scanner = null;
try {
scanner = new Scanner(foundFile);
} catch (FileNotFoundException e) {
Assert.fail("Unable to locate file: " + e.getMessage() + " file: " + foundFile.getAbsolutePath());
}
LOG.warn("Found a file with a prohibited string. Printing contents:");
while (scanner.hasNextLine()) {
LOG.warn("LINE: " + scanner.nextLine());
}
Assert.fail(
"Found a file " + foundFile + " with a prohibited string (one of " + Arrays.toString(prohibited) + "). " +
"Excerpts:" + System.lineSeparator() + prohibitedExcerpts);
}
}
public static boolean verifyStringsInNamedLogFiles(
final String[] mustHave, final String fileName) {
List<String> mustHaveList = Arrays.asList(mustHave);
File cwd = new File("target/" + YARN_CONFIGURATION.get(TEST_CLUSTER_NAME_KEY));
if (!cwd.exists() || !cwd.isDirectory()) {
return false;
}
File foundFile = TestUtils.findFile(cwd.getAbsolutePath(), new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (fileName != null && !name.equals(fileName)) {
return false;
}
File f = new File(dir.getAbsolutePath() + "/" + name);
LOG.info("Searching in {}", f.getAbsolutePath());
try (Scanner scanner = new Scanner(f)) {
Set<String> foundSet = new HashSet<>(mustHave.length);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
for (String str : mustHave) {
if (lineFromFile.contains(str)) {
foundSet.add(str);
}
}
if (foundSet.containsAll(mustHaveList)) {
return true;
}
}
} catch (FileNotFoundException e) {
LOG.warn("Unable to locate file: " + e.getMessage() + " file: " + f.getAbsolutePath());
}
return false;
}
});
if (foundFile != null) {
LOG.info("Found string {} in {}.", Arrays.toString(mustHave), foundFile.getAbsolutePath());
return true;
} else {
return false;
}
}
public static boolean verifyTokenKindInContainerCredentials(final Collection<String> tokens, final String containerId)
throws IOException {
File cwd = new File("target/" + YARN_CONFIGURATION.get(TEST_CLUSTER_NAME_KEY));
if (!cwd.exists() || !cwd.isDirectory()) {
return false;
}
File containerTokens = TestUtils.findFile(cwd.getAbsolutePath(), new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals(containerId + ".tokens");
}
});
if (containerTokens != null) {
LOG.info("Verifying tokens in {}", containerTokens.getAbsolutePath());
Credentials tmCredentials = Credentials.readTokenStorageFile(containerTokens, new Configuration());
Collection<Token<? extends TokenIdentifier>> userTokens = tmCredentials.getAllTokens();
Set<String> tokenKinds = new HashSet<>(4);
for (Token<? extends TokenIdentifier> token : userTokens) {
tokenKinds.add(token.getKind().toString());
}
return tokenKinds.containsAll(tokens);
} else {
LOG.warn("Unable to find credential file for container {}", containerId);
return false;
}
}
public static String getContainerIdByLogName(String logName) {
File cwd = new File("target/" + YARN_CONFIGURATION.get(TEST_CLUSTER_NAME_KEY));
File containerLog = TestUtils.findFile(cwd.getAbsolutePath(), new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals(logName);
}
});
if (containerLog != null) {
return containerLog.getParentFile().getName();
} else {
throw new IllegalStateException("No container has log named " + logName);
}
}
public static void sleep(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
LOG.warn("Interruped", e);
}
}
public static int getRunningContainers() {
int count = 0;
for (int nmId = 0; nmId < NUM_NODEMANAGERS; nmId++) {
NodeManager nm = yarnCluster.getNodeManager(nmId);
ConcurrentMap<ContainerId, Container> containers = nm.getNMContext().getContainers();
count += containers.size();
}
return count;
}
protected ApplicationReport getOnlyApplicationReport() throws IOException, YarnException {
final YarnClient yarnClient = getYarnClient();
checkState(yarnClient != null);
final List<ApplicationReport> apps = yarnClient.getApplications(EnumSet.of(YarnApplicationState.RUNNING));
assertEquals(1, apps.size()); // Only one running
return apps.get(0);
}
public static void startYARNSecureMode(YarnConfiguration conf, String principal, String keytab) {
start(conf, principal, keytab, false);
}
public static void startYARNWithConfig(YarnConfiguration conf) {
startYARNWithConfig(conf, false);
}
public static void startYARNWithConfig(YarnConfiguration conf, boolean withDFS) {
start(conf, null, null, withDFS);
}
private static void start(YarnConfiguration conf, String principal, String keytab, boolean withDFS) {
// set the home directory to a temp directory. Flink on YARN is using the home dir to distribute the file
File homeDir = null;
try {
homeDir = tmp.newFolder();
} catch (IOException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
System.setProperty("user.home", homeDir.getAbsolutePath());
String uberjarStartLoc = "..";
LOG.info("Trying to locate uberjar in {}", new File(uberjarStartLoc).getAbsolutePath());
flinkUberjar = TestUtils.findFile(uberjarStartLoc, new TestUtils.RootDirFilenameFilter());
Assert.assertNotNull("Flink uberjar not found", flinkUberjar);
String flinkDistRootDir = flinkUberjar.getParentFile().getParent();
flinkLibFolder = flinkUberjar.getParentFile(); // the uberjar is located in lib/
Assert.assertNotNull("Flink flinkLibFolder not found", flinkLibFolder);
Assert.assertTrue("lib folder not found", flinkLibFolder.exists());
Assert.assertTrue("lib folder not found", flinkLibFolder.isDirectory());
if (!flinkUberjar.exists()) {
Assert.fail("Unable to locate yarn-uberjar.jar");
}
try {
LOG.info("Starting up MiniYARNCluster");
if (yarnCluster == null) {
final String testName = conf.get(YarnTestBase.TEST_CLUSTER_NAME_KEY);
yarnCluster = new MiniYARNCluster(
testName == null ? "YarnTest_" + UUID.randomUUID() : testName,
NUM_NODEMANAGERS,
1,
1);
yarnCluster.init(conf);
yarnCluster.start();
}
Map<String, String> map = new HashMap<String, String>(System.getenv());
File flinkConfDirPath = TestUtils.findFile(flinkDistRootDir, new ContainsName(new String[]{"flink-conf.yaml"}));
Assert.assertNotNull(flinkConfDirPath);
final String confDirPath = flinkConfDirPath.getParentFile().getAbsolutePath();
globalConfiguration = GlobalConfiguration.loadConfiguration(confDirPath);
//copy conf dir to test temporary workspace location
tempConfPathForSecureRun = tmp.newFolder("conf");
FileUtils.copyDirectory(new File(confDirPath), tempConfPathForSecureRun);
BootstrapTools.writeConfiguration(
globalConfiguration,
new File(tempConfPathForSecureRun, "flink-conf.yaml"));
String configDir = tempConfPathForSecureRun.getAbsolutePath();
LOG.info("Temporary Flink configuration directory to be used for secure test: {}", configDir);
Assert.assertNotNull(configDir);
map.put(ConfigConstants.ENV_FLINK_CONF_DIR, configDir);
File targetTestClassesFolder = new File("target/test-classes");
writeYarnSiteConfigXML(conf, targetTestClassesFolder);
if (withDFS) {
LOG.info("Starting up MiniDFSCluster");
setMiniDFSCluster(targetTestClassesFolder);
}
map.put("IN_TESTS", "yes we are in tests"); // see YarnClusterDescriptor() for more infos
map.put("YARN_CONF_DIR", targetTestClassesFolder.getAbsolutePath());
TestBaseUtils.setEnv(map);
Assert.assertTrue(yarnCluster.getServiceState() == Service.STATE.STARTED);
// wait for the nodeManagers to connect
while (!yarnCluster.waitForNodeManagersToConnect(500)) {
LOG.info("Waiting for Nodemanagers to connect");
}
} catch (Exception ex) {
ex.printStackTrace();
LOG.error("setup failure", ex);
Assert.fail();
}
}
private static void setMiniDFSCluster(File targetTestClassesFolder) throws Exception {
if (miniDFSCluster == null) {
Configuration hdfsConfiguration = new Configuration();
hdfsConfiguration.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, tmpHDFS.getRoot().getAbsolutePath());
miniDFSCluster = new MiniDFSCluster
.Builder(hdfsConfiguration)
.numDataNodes(2)
.build();
miniDFSCluster.waitClusterUp();
hdfsConfiguration = miniDFSCluster.getConfiguration(0);
writeHDFSSiteConfigXML(hdfsConfiguration, targetTestClassesFolder);
YARN_CONFIGURATION.addResource(hdfsConfiguration);
}
}
/**
* Default @BeforeClass impl. Overwrite this for passing a different configuration
*/
@BeforeClass
public static void setup() throws Exception {
startYARNWithConfig(YARN_CONFIGURATION, false);
}
// -------------------------- Runner -------------------------- //
protected static ByteArrayOutputStream outContent;
protected static ByteArrayOutputStream errContent;
enum RunTypes {
YARN_SESSION, CLI_FRONTEND
}
/**
* This method returns once the "startedAfterString" has been seen.
*/
protected Runner startWithArgs(String[] args, String startedAfterString, RunTypes type) throws IOException {
LOG.info("Running with args {}", Arrays.toString(args));
outContent = new ByteArrayOutputStream();
errContent = new ByteArrayOutputStream();
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out);
PrintStream stdinPrintStream = new PrintStream(out);
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
System.setIn(in);
final int startTimeoutSeconds = 60;
Runner runner = new Runner(
args,
flinkConfiguration,
CliFrontend.getConfigurationDirectoryFromEnv(),
type,
0,
stdinPrintStream);
runner.setName("Frontend (CLI/YARN Client) runner thread (startWithArgs()).");
runner.start();
for (int second = 0; second < startTimeoutSeconds; second++) {
sleep(1000);
// check output for correct TaskManager startup.
if (outContent.toString().contains(startedAfterString)
|| errContent.toString().contains(startedAfterString)) {
LOG.info("Found expected output in redirected streams");
return runner;
}
// check if thread died
if (!runner.isAlive()) {
resetStreamsAndSendOutput();
if (runner.getRunnerError() != null) {
throw new RuntimeException("Runner failed with exception.", runner.getRunnerError());
}
Assert.fail("Runner thread died before the test was finished.");
}
}
resetStreamsAndSendOutput();
Assert.fail("During the timeout period of " + startTimeoutSeconds + " seconds the " +
"expected string did not show up");
return null;
}
protected void runWithArgs(String[] args, String terminateAfterString, String[] failOnStrings, RunTypes type, int returnCode) throws IOException {
runWithArgs(args, terminateAfterString, failOnStrings, type, returnCode, Collections::emptyList);
}
/**
* The test has been passed once the "terminateAfterString" has been seen.
* @param args Command line arguments for the runner
* @param terminateAfterString the runner is searching the stdout and stderr for this string. as soon as it appears, the test has passed
* @param failOnPatterns The runner is searching stdout and stderr for the pattern (regexp) specified here. If one appears, the test has failed
* @param type Set the type of the runner
* @param expectedReturnValue Expected return code from the runner.
* @param logMessageSupplier Supplier for log messages
*/
protected void runWithArgs(String[] args, String terminateAfterString, String[] failOnPatterns, RunTypes type, int expectedReturnValue, Supplier<Collection<String>> logMessageSupplier) throws IOException {
LOG.info("Running with args {}", Arrays.toString(args));
outContent = new ByteArrayOutputStream();
errContent = new ByteArrayOutputStream();
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out);
PrintStream stdinPrintStream = new PrintStream(out);
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
System.setIn(in);
// we wait for at most three minutes
final int startTimeoutSeconds = 180;
final long deadline = System.currentTimeMillis() + (startTimeoutSeconds * 1000);
Runner runner = new Runner(
args,
flinkConfiguration,
CliFrontend.getConfigurationDirectoryFromEnv(),
type,
expectedReturnValue,
stdinPrintStream);
runner.start();
boolean expectedStringSeen = false;
boolean testPassedFromLog4j = false;
long shutdownTimeout = 30000L;
do {
sleep(1000);
String outContentString = outContent.toString();
String errContentString = errContent.toString();
if (failOnPatterns != null) {
for (String failOnString : failOnPatterns) {
Pattern pattern = Pattern.compile(failOnString);
if (pattern.matcher(outContentString).find() || pattern.matcher(errContentString).find()) {
LOG.warn("Failing test. Output contained illegal string '" + failOnString + "'");
resetStreamsAndSendOutput();
// stopping runner.
runner.sendStop();
// wait for the thread to stop
try {
runner.join(shutdownTimeout);
} catch (InterruptedException e) {
LOG.warn("Interrupted while stopping runner", e);
}
Assert.fail("Output contained illegal string '" + failOnString + "'");
}
}
}
for (String logMessage : logMessageSupplier.get()) {
if (logMessage.contains(terminateAfterString)) {
testPassedFromLog4j = true;
LOG.info("Found expected output in logging event {}", logMessage);
}
}
if (outContentString.contains(terminateAfterString) || errContentString.contains(terminateAfterString) || testPassedFromLog4j) {
expectedStringSeen = true;
LOG.info("Found expected output in redirected streams");
// send "stop" command to command line interface
LOG.info("RunWithArgs: request runner to stop");
runner.sendStop();
// wait for the thread to stop
try {
runner.join(shutdownTimeout);
}
catch (InterruptedException e) {
LOG.warn("Interrupted while stopping runner", e);
}
LOG.warn("RunWithArgs runner stopped.");
}
else {
// check if thread died
if (!runner.isAlive()) {
// leave loop: the runner died, so we can not expect new strings to show up.
break;
}
}
}
while (runner.getRunnerError() == null && !expectedStringSeen && System.currentTimeMillis() < deadline);
resetStreamsAndSendOutput();
if (runner.getRunnerError() != null) {
// this lets the test fail.
throw new RuntimeException("Runner failed", runner.getRunnerError());
}
Assert.assertTrue("During the timeout period of " + startTimeoutSeconds + " seconds the " +
"expected string \"" + terminateAfterString + "\" did not show up.", expectedStringSeen);
LOG.info("Test was successful");
}
protected static void resetStreamsAndSendOutput() {
System.setOut(ORIGINAL_STDOUT);
System.setErr(ORIGINAL_STDERR);
System.setIn(ORIGINAL_STDIN);
LOG.info("Sending stdout content through logger: \n\n{}\n\n", outContent.toString());
LOG.info("Sending stderr content through logger: \n\n{}\n\n", errContent.toString());
}
/**
* Utility class to run yarn jobs.
*/
protected static class Runner extends Thread {
private final String[] args;
private final org.apache.flink.configuration.Configuration configuration;
private final String configurationDirectory;
private final int expectedReturnValue;
private final PrintStream stdinPrintStream;
private RunTypes type;
private FlinkYarnSessionCli yCli;
private Throwable runnerError;
public Runner(
String[] args,
org.apache.flink.configuration.Configuration configuration,
String configurationDirectory,
RunTypes type,
int expectedReturnValue,
PrintStream stdinPrintStream) {
this.args = args;
this.configuration = Preconditions.checkNotNull(configuration);
this.configurationDirectory = Preconditions.checkNotNull(configurationDirectory);
this.type = type;
this.expectedReturnValue = expectedReturnValue;
this.stdinPrintStream = Preconditions.checkNotNull(stdinPrintStream);
}
@Override
public void run() {
try {
int returnValue;
switch (type) {
case YARN_SESSION:
yCli = new FlinkYarnSessionCli(
configuration,
configurationDirectory,
"",
"",
true);
returnValue = yCli.run(args);
break;
case CLI_FRONTEND:
try {
CliFrontend cli = new CliFrontend(
configuration,
CliFrontend.loadCustomCommandLines(configuration, configurationDirectory));
returnValue = cli.parseParameters(args);
} catch (Exception e) {
throw new RuntimeException("Failed to execute the following args with CliFrontend: "
+ Arrays.toString(args), e);
}
break;
default:
throw new RuntimeException("Unknown type " + type);
}
if (returnValue != this.expectedReturnValue) {
Assert.fail("The YARN session returned with unexpected value=" + returnValue + " expected=" + expectedReturnValue);
}
} catch (Throwable t) {
LOG.info("Runner stopped with exception", t);
// save error.
this.runnerError = t;
}
}
/** Stops the Yarn session. */
public void sendStop() {
stdinPrintStream.println("stop");
}
public Throwable getRunnerError() {
return runnerError;
}
}
// -------------------------- Tear down -------------------------- //
@AfterClass
public static void teardown() throws Exception {
if (yarnCluster != null) {
LOG.info("Stopping MiniYarn Cluster");
yarnCluster.stop();
yarnCluster = null;
}
if (miniDFSCluster != null) {
LOG.info("Stopping MiniDFS Cluster");
miniDFSCluster.shutdown();
miniDFSCluster = null;
}
// Unset FLINK_CONF_DIR, as it might change the behavior of other tests
Map<String, String> map = new HashMap<>(System.getenv());
map.remove(ConfigConstants.ENV_FLINK_CONF_DIR);
map.remove("YARN_CONF_DIR");
map.remove("IN_TESTS");
TestBaseUtils.setEnv(map);
if (tempConfPathForSecureRun != null) {
FileUtil.fullyDelete(tempConfPathForSecureRun);
tempConfPathForSecureRun = null;
}
if (yarnSiteXML != null) {
yarnSiteXML.delete();
}
if (hdfsSiteXML != null) {
hdfsSiteXML.delete();
}
// When we are on CI, we copy the temp files of JUnit (containing the MiniYARNCluster log files)
// to <flinkRoot>/target/flink-yarn-tests-*.
// The files from there are picked up by the tools/ci/* scripts to upload them.
if (isOnCI()) {
File target = new File("../target" + YARN_CONFIGURATION.get(TEST_CLUSTER_NAME_KEY));
if (!target.mkdirs()) {
LOG.warn("Error creating dirs to {}", target);
}
File src = tmp.getRoot();
LOG.info("copying the final files from {} to {}", src.getAbsolutePath(), target.getAbsolutePath());
try {
FileUtils.copyDirectoryToDirectory(src, target);
} catch (IOException e) {
LOG.warn("Error copying the final files from {} to {}: msg: {}", src.getAbsolutePath(), target.getAbsolutePath(), e.getMessage(), e);
}
}
}
public static boolean isOnCI() {
return System.getenv("IS_CI") != null && System.getenv("IS_CI").equals("true");
}
protected void waitApplicationFinishedElseKillIt(
ApplicationId applicationId,
Duration timeout,
YarnClusterDescriptor yarnClusterDescriptor,
int sleepIntervalInMS) throws Exception {
Deadline deadline = Deadline.now().plus(timeout);
YarnApplicationState state = getYarnClient().getApplicationReport(applicationId).getYarnApplicationState();
while (state != YarnApplicationState.FINISHED) {
if (state == YarnApplicationState.FAILED || state == YarnApplicationState.KILLED) {
Assert.fail("Application became FAILED or KILLED while expecting FINISHED");
}
if (deadline.isOverdue()) {
yarnClusterDescriptor.killCluster(applicationId);
Assert.fail("Application didn't finish before timeout");
}
sleep(sleepIntervalInMS);
state = getYarnClient().getApplicationReport(applicationId).getYarnApplicationState();
}
}
/**
* Wrapper around a {@link Scanner} that buffers the last N lines read.
*/
private static class BufferingScanner {
private final Scanner scanner;
private final int numLinesBuffered;
private final List<String> bufferedLines;
BufferingScanner(Scanner scanner, int numLinesBuffered) {
this.scanner = scanner;
this.numLinesBuffered = numLinesBuffered;
this.bufferedLines = new ArrayList<>(numLinesBuffered);
}
public boolean hasNextLine() {
return scanner.hasNextLine();
}
public String nextLine() {
if (bufferedLines.size() == numLinesBuffered) {
bufferedLines.remove(0);
}
String line = scanner.nextLine();
bufferedLines.add(line);
return line;
}
public List<String> getPreviousLines() {
return new ArrayList<>(bufferedLines);
}
}
}
| apache-2.0 |
GabrielBrascher/cloudstack | plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/manager/VmwareStorageManager.java | 2594 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.hypervisor.vmware.manager;
import org.apache.cloudstack.storage.to.TemplateObjectTO;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.BackupSnapshotCommand;
import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
import com.cloud.agent.api.CreateVMSnapshotCommand;
import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
import com.cloud.agent.api.DeleteVMSnapshotCommand;
import com.cloud.agent.api.RevertToVMSnapshotCommand;
import com.cloud.agent.api.storage.CopyVolumeCommand;
import com.cloud.agent.api.storage.CreateEntityDownloadURLCommand;
import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
public interface VmwareStorageManager {
Answer execute(VmwareHostService hostService, PrimaryStorageDownloadCommand cmd);
Answer execute(VmwareHostService hostService, BackupSnapshotCommand cmd);
Answer execute(VmwareHostService hostService, CreatePrivateTemplateFromVolumeCommand cmd);
Answer execute(VmwareHostService hostService, CreatePrivateTemplateFromSnapshotCommand cmd);
Answer execute(VmwareHostService hostService, CopyVolumeCommand cmd);
Answer execute(VmwareHostService hostService, CreateVolumeFromSnapshotCommand cmd);
Answer execute(VmwareHostService hostService, CreateVMSnapshotCommand cmd);
Answer execute(VmwareHostService hostService, DeleteVMSnapshotCommand cmd);
Answer execute(VmwareHostService hostService, RevertToVMSnapshotCommand cmd);
boolean execute(VmwareHostService hostService, CreateEntityDownloadURLCommand cmd);
public void createOva(String path, String name, int archiveTimeout);
public String createOvaForTemplate(TemplateObjectTO template, int archiveTimeout);
}
| apache-2.0 |
Fitzoh/spring-security-oauth | spring-security-oauth2/src/test/java/org/springframework/security/oauth2/http/converter/jaxb/JaxbOAuth2ExceptionMessageConverterTests.java | 9451 | /*
* Copyright 2011-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.security.oauth2.http.converter.jaxb;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.security.oauth2.common.exceptions.*;
/**
*
* @author Rob Winch
*
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({ System.class, JaxbOAuth2AccessToken.class })
public class JaxbOAuth2ExceptionMessageConverterTests extends BaseJaxbMessageConverterTest {
private JaxbOAuth2ExceptionMessageConverter converter;
private static String DETAILS = "some detail";
@Before
public void before() throws Exception {
converter = new JaxbOAuth2ExceptionMessageConverter();
}
@Test
public void writeInvalidClient() throws IOException {
OAuth2Exception oauthException = new InvalidClientException(DETAILS);
String expected = createResponse(oauthException.getOAuth2ErrorCode());
converter.write(oauthException, contentType, outputMessage);
assertEquals(expected, getOutput());
}
@Test
public void writeInvalidGrant() throws Exception {
OAuth2Exception oauthException = new InvalidGrantException(DETAILS);
String expected = createResponse(oauthException.getOAuth2ErrorCode());
converter.write(oauthException, contentType, outputMessage);
assertEquals(expected, getOutput());
}
@Test
public void writeInvalidRequest() throws Exception {
OAuth2Exception oauthException = new InvalidRequestException(DETAILS);
String expected = createResponse(oauthException.getOAuth2ErrorCode());
converter.write(oauthException, contentType, outputMessage);
assertEquals(expected, getOutput());
}
@Test
public void writeInvalidScope() throws Exception {
OAuth2Exception oauthException = new InvalidScopeException(DETAILS);
String expected = createResponse(oauthException.getOAuth2ErrorCode());
converter.write(oauthException, contentType, outputMessage);
assertEquals(expected, getOutput());
}
@Test
public void writeUnsupportedGrantType() throws Exception {
OAuth2Exception oauthException = new UnsupportedGrantTypeException(DETAILS);
String expected = createResponse(oauthException.getOAuth2ErrorCode());
converter.write(oauthException, contentType, outputMessage);
assertEquals(expected, getOutput());
}
@Test
public void writeUnauthorizedClient() throws Exception {
OAuth2Exception oauthException = new UnauthorizedClientException(DETAILS);
String expected = createResponse(oauthException.getOAuth2ErrorCode());
converter.write(oauthException, contentType, outputMessage);
assertEquals(expected, getOutput());
}
@Test
public void writeAccessDenied() throws Exception {
OAuth2Exception oauthException = new UserDeniedAuthorizationException(DETAILS);
String expected = createResponse(oauthException.getOAuth2ErrorCode());
converter.write(oauthException, contentType, outputMessage);
assertEquals(expected, getOutput());
}
@Test
public void writeRedirectUriMismatch() throws Exception {
OAuth2Exception oauthException = new RedirectMismatchException(DETAILS);
String expected = createResponse(oauthException.getOAuth2ErrorCode());
converter.write(oauthException, contentType, outputMessage);
assertEquals(expected, getOutput());
}
@Test
public void writeInvalidToken() throws Exception {
OAuth2Exception oauthException = new InvalidTokenException(DETAILS);
String expected = createResponse(oauthException.getOAuth2ErrorCode());
converter.write(oauthException, contentType, outputMessage);
assertEquals(expected, getOutput());
}
@Test
public void writeOAuth2Exception() throws Exception {
OAuth2Exception oauthException = new OAuth2Exception(DETAILS);
String expected = createResponse(oauthException.getOAuth2ErrorCode());
converter.write(oauthException, contentType, outputMessage);
assertEquals(expected, getOutput());
}
// SECOAUTH-311
@Test
public void writeCreatesNewUnmarshaller() throws Exception {
useMockJAXBContext(converter, JaxbOAuth2Exception.class);
OAuth2Exception oauthException = new OAuth2Exception(DETAILS);
converter.write(oauthException, contentType, outputMessage);
verify(context).createMarshaller();
converter.write(oauthException, contentType, outputMessage);
verify(context,times(2)).createMarshaller();
}
@Test
public void readInvalidGrant() throws Exception {
String accessToken = createResponse(OAuth2Exception.INVALID_GRANT);
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
@SuppressWarnings("unused")
InvalidGrantException result = (InvalidGrantException) converter.read(OAuth2Exception.class, inputMessage);
}
@Test
public void readInvalidRequest() throws Exception {
String accessToken = createResponse(OAuth2Exception.INVALID_REQUEST);
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
@SuppressWarnings("unused")
InvalidRequestException result = (InvalidRequestException) converter.read(OAuth2Exception.class, inputMessage);
}
@Test
public void readInvalidScope() throws Exception {
String accessToken = createResponse(OAuth2Exception.INVALID_SCOPE);
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
@SuppressWarnings("unused")
InvalidScopeException result = (InvalidScopeException) converter.read(OAuth2Exception.class, inputMessage);
}
@Test
public void readUnsupportedGrantType() throws Exception {
String accessToken = createResponse(OAuth2Exception.UNSUPPORTED_GRANT_TYPE);
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
@SuppressWarnings("unused")
UnsupportedGrantTypeException result = (UnsupportedGrantTypeException) converter.read(OAuth2Exception.class, inputMessage);
}
@Test
public void readUnauthorizedClient() throws Exception {
String accessToken = createResponse(OAuth2Exception.UNAUTHORIZED_CLIENT);
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
@SuppressWarnings("unused")
UnauthorizedClientException result = (UnauthorizedClientException) converter.read(OAuth2Exception.class,
inputMessage);
}
@Test
public void readAccessDenied() throws Exception {
String accessToken = createResponse(OAuth2Exception.ACCESS_DENIED);
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
@SuppressWarnings("unused")
UserDeniedAuthorizationException result = (UserDeniedAuthorizationException) converter.read(
OAuth2Exception.class, inputMessage);
}
@Test
public void readRedirectUriMismatch() throws Exception {
String accessToken = createResponse(OAuth2Exception.REDIRECT_URI_MISMATCH);
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
@SuppressWarnings("unused")
RedirectMismatchException result = (RedirectMismatchException) converter.read(OAuth2Exception.class,
inputMessage);
}
@Test
public void readInvalidToken() throws Exception {
String accessToken = createResponse(OAuth2Exception.INVALID_TOKEN);
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
@SuppressWarnings("unused")
InvalidTokenException result = (InvalidTokenException) converter.read(OAuth2Exception.class, inputMessage);
}
@Test
public void readUndefinedException() throws Exception {
String accessToken = createResponse("notdefinedcode");
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
@SuppressWarnings("unused")
OAuth2Exception result = converter.read(OAuth2Exception.class, inputMessage);
}
@Test
public void readInvalidClient() throws IOException {
String accessToken = createResponse(OAuth2Exception.INVALID_CLIENT);
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
@SuppressWarnings("unused")
InvalidClientException result = (InvalidClientException) converter.read(InvalidClientException.class,
inputMessage);
}
// SECOAUTH-311
@Test
public void readCreatesNewUnmarshaller() throws Exception {
useMockJAXBContext(converter, JaxbOAuth2Exception.class);
String accessToken = createResponse(OAuth2Exception.ACCESS_DENIED);
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
converter.read(OAuth2Exception.class, inputMessage);
verify(context).createUnmarshaller();
when(inputMessage.getBody()).thenReturn(createInputStream(accessToken));
converter.read(OAuth2Exception.class, inputMessage);
verify(context,times(2)).createUnmarshaller();
}
private String createResponse(String error) {
return "<oauth><error_description>some detail</error_description><error>" + error + "</error></oauth>";
}
}
| apache-2.0 |
smgoller/geode | geode-connectors/src/acceptanceTest/java/org/apache/geode/connectors/jdbc/internal/MySqlTableMetaDataManagerIntegrationTest.java | 1825 | /*
* 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.geode.connectors.jdbc.internal;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.ClassRule;
import org.apache.geode.connectors.jdbc.internal.configuration.RegionMapping;
import org.apache.geode.connectors.jdbc.test.junit.rules.DatabaseConnectionRule;
import org.apache.geode.connectors.jdbc.test.junit.rules.MySqlConnectionRule;
public class MySqlTableMetaDataManagerIntegrationTest extends TableMetaDataManagerIntegrationTest {
private static final URL COMPOSE_RESOURCE_PATH =
MySqlTableMetaDataManagerIntegrationTest.class.getResource("/mysql.yml");
@ClassRule
public static DatabaseConnectionRule dbRule =
new MySqlConnectionRule.Builder().file(COMPOSE_RESOURCE_PATH.getPath()).build();
@Override
public Connection getConnection() throws SQLException {
return dbRule.getConnection();
}
@Override
protected void setSchemaOrCatalogOnMapping(RegionMapping regionMapping, String name) {
regionMapping.setCatalog(name);
}
}
| apache-2.0 |
yongli82/generator-jhipster | generators/server/templates/src/main/java/package/domain/_OAuth2AuthenticationCode.java | 2176 | <%#
Copyright 2013-2017 the original author or authors from the JHipster project.
This file is part of the JHipster project, see https://jhipster.github.io/
for more information.
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 <%=packageName%>.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import java.io.Serializable;
import java.util.UUID;
@Document(collection = "OAUTH_AUTHENTICATION_CODE")
public class OAuth2AuthenticationCode implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String id;
private String code;
private OAuth2Authentication authentication;
@PersistenceConstructor
public OAuth2AuthenticationCode(String code, OAuth2Authentication authentication) {
this.id = UUID.randomUUID().toString();
this.code = code;
this.authentication = authentication;
}
public String getCode() {
return code;
}
public OAuth2Authentication getAuthentication() {
return authentication;
}
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
OAuth2AuthenticationCode that = (OAuth2AuthenticationCode) o;
if (id != null ? !id.equals(that.id) : that.id != null) { return false; }
return true;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
| apache-2.0 |
coding0011/elasticsearch | buildSrc/src/main/java/org/elasticsearch/gradle/precommit/LoggerUsageTask.java | 2844 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.gradle.precommit;
import org.elasticsearch.gradle.LoggedExec;
import org.gradle.api.file.FileCollection;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.CacheableTask;
import org.gradle.api.tasks.Classpath;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.SkipWhenEmpty;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.TaskAction;
import java.io.File;
/**
* Runs LoggerUsageCheck on a set of directories.
*/
@CacheableTask
public class LoggerUsageTask extends PrecommitTask {
private FileCollection classpath;
public LoggerUsageTask() {
setDescription("Runs LoggerUsageCheck on output directories of all source sets");
}
@TaskAction
public void runLoggerUsageTask() {
LoggedExec.javaexec(getProject(), spec -> {
spec.setMain("org.elasticsearch.test.loggerusage.ESLoggerUsageChecker");
spec.classpath(getClasspath());
getClassDirectories().forEach(spec::args);
});
}
@Classpath
public FileCollection getClasspath() {
return classpath;
}
public void setClasspath(FileCollection classpath) {
this.classpath = classpath;
}
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
@SkipWhenEmpty
public FileCollection getClassDirectories() {
return getProject().getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().stream()
// Don't pick up all source sets like the java9 ones as logger-check doesn't support the class format
.filter(sourceSet -> sourceSet.getName().equals(SourceSet.MAIN_SOURCE_SET_NAME)
|| sourceSet.getName().equals(SourceSet.TEST_SOURCE_SET_NAME))
.map(sourceSet -> sourceSet.getOutput().getClassesDirs())
.reduce(FileCollection::plus)
.orElse(getProject().files())
.filter(File::exists);
}
}
| apache-2.0 |
hgl888/buck | src/com/facebook/buck/ocaml/AbstractOCamlBuildContext.java | 11690 | /*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.ocaml;
import com.facebook.buck.cxx.CxxPreprocessorInput;
import com.facebook.buck.cxx.CxxSource;
import com.facebook.buck.cxx.NativeLinkableInput;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.UnflavoredBuildTarget;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.RuleKeyAppendable;
import com.facebook.buck.util.MoreIterables;
import com.facebook.buck.util.immutables.BuckStyleImmutable;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import org.immutables.value.Value;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
@Value.Immutable
@BuckStyleImmutable
abstract class AbstractOCamlBuildContext implements RuleKeyAppendable {
static final String OCAML_COMPILED_BYTECODE_DIR = "bc";
static final String OCAML_COMPILED_DIR = "opt";
private static final String OCAML_GENERATED_SOURCE_DIR = "gen";
static final Path DEFAULT_OCAML_INTEROP_INCLUDE_DIR = Paths.get("/usr/local/lib/ocaml");
public abstract BuildTarget getBuildTarget();
public abstract boolean isLibrary();
public abstract List<String> getFlags();
public abstract List<Path> getInput();
public abstract List<String> getIncludes();
public abstract NativeLinkableInput getLinkableInput();
public abstract List<OCamlLibrary> getOCamlInput();
public abstract CxxPreprocessorInput getCxxPreprocessorInput();
public abstract List<String> getBytecodeIncludes();
public abstract ImmutableSortedSet<BuildRule> getCompileDeps();
public abstract ImmutableSortedSet<BuildRule> getBytecodeCompileDeps();
public abstract ImmutableSortedSet<BuildRule> getBytecodeLinkDeps();
public abstract Optional<Path> getOcamlDepTool();
public abstract Optional<Path> getOcamlCompiler();
public abstract Optional<Path> getOcamlDebug();
public abstract Optional<Path> getYaccCompiler();
public abstract Optional<Path> getLexCompiler();
public abstract Optional<Path> getOcamlBytecodeCompiler();
protected abstract List<String> getCFlags();
protected abstract Optional<String> getOCamlInteropIncludesDir();
protected abstract List<String> getLdFlags();
public ImmutableList<Path> getCInput() {
return FluentIterable.from(getInput())
.filter(OCamlUtil.ext(OCamlCompilables.OCAML_C))
.toSet()
.asList();
}
public ImmutableList<Path> getLexInput() {
return FluentIterable.from(getInput())
.filter(OCamlUtil.ext(OCamlCompilables.OCAML_MLL))
.toSet()
.asList();
}
public ImmutableList<Path> getYaccInput() {
return FluentIterable.from(getInput())
.filter(OCamlUtil.ext(OCamlCompilables.OCAML_MLY))
.toSet()
.asList();
}
public ImmutableList<Path> getMLInput() {
return FluentIterable.from(getInput())
.filter(OCamlUtil.ext(OCamlCompilables.OCAML_ML, OCamlCompilables.OCAML_MLI))
.append(getLexOutput(getLexInput()))
.append(getYaccOutput(getYaccInput()))
.toSet()
.asList();
}
private static Path getArchiveOutputPath(UnflavoredBuildTarget target) {
return BuildTargets.getGenPath(
target,
"%s/lib" + target.getShortName() + OCamlCompilables.OCAML_CMXA);
}
private static Path getArchiveBytecodeOutputPath(UnflavoredBuildTarget target) {
return BuildTargets.getGenPath(
target,
"%s/lib" + target.getShortName() + OCamlCompilables.OCAML_CMA);
}
public Path getOutput() {
return getOutputPath(getBuildTarget(), isLibrary());
}
public static Path getOutputPath(BuildTarget target, boolean isLibrary) {
UnflavoredBuildTarget plainTarget = target.getUnflavoredBuildTarget();
if (isLibrary) {
return getArchiveOutputPath(plainTarget);
} else {
return BuildTargets.getScratchPath(
plainTarget,
"%s/" + plainTarget.getShortName() + ".opt");
}
}
public Path getBytecodeOutput() {
UnflavoredBuildTarget plainTarget = getBuildTarget().getUnflavoredBuildTarget();
if (isLibrary()) {
return getArchiveBytecodeOutputPath(plainTarget);
} else {
return BuildTargets.getScratchPath(
plainTarget,
"%s/" + plainTarget.getShortName());
}
}
public Path getGeneratedSourceDir() {
return getOutput().getParent().resolve(OCAML_GENERATED_SOURCE_DIR);
}
public Path getCompileOutputDir() {
return getCompileOutputDir(getBuildTarget(), isLibrary());
}
public static Path getCompileOutputDir(BuildTarget buildTarget, boolean isLibrary) {
return getOutputPath(buildTarget, isLibrary).getParent().resolve(
OCAML_COMPILED_DIR);
}
public Path getCompileBytecodeOutputDir() {
return getOutput().getParent().resolve(OCAML_COMPILED_BYTECODE_DIR);
}
public Path getCOutput(Path cSrc) {
String inputFileName = cSrc.getFileName().toString();
String outputFileName = inputFileName
.replaceFirst(
OCamlCompilables.OCAML_C_REGEX,
OCamlCompilables.OCAML_O);
return getCompileOutputDir().resolve(outputFileName);
}
public Function<Path, Path> toCOutput() {
return new Function<Path, Path>() {
@Override
public Path apply(Path input) {
return getCOutput(input);
}
};
}
public ImmutableList<String> getIncludeDirectories(boolean isBytecode, boolean excludeDeps) {
ImmutableSet.Builder<String> includeDirs = ImmutableSet.builder();
for (Path mlFile : getMLInput()) {
Path parent = mlFile.getParent();
if (parent != null) {
includeDirs.add(parent.toString());
}
}
if (!excludeDeps) {
includeDirs.addAll(isBytecode ? this.getBytecodeIncludes() : this.getIncludes());
}
return ImmutableList.copyOf(includeDirs.build());
}
public ImmutableList<String> getIncludeFlags(boolean isBytecode, boolean excludeDeps) {
return ImmutableList.copyOf(
MoreIterables.zipAndConcat(
Iterables.cycle(OCamlCompilables.OCAML_INCLUDE_FLAG),
getIncludeDirectories(isBytecode, excludeDeps)));
}
public ImmutableList<String> getBytecodeIncludeFlags() {
return ImmutableList.copyOf(
MoreIterables.zipAndConcat(
Iterables.cycle(OCamlCompilables.OCAML_INCLUDE_FLAG),
getBytecodeIncludeDirectories()));
}
public ImmutableList<String> getBytecodeIncludeDirectories() {
ImmutableList.Builder<String> includesBuilder = ImmutableList.builder();
includesBuilder.addAll(getIncludeDirectories(true, /* excludeDeps */ true));
includesBuilder.add(getCompileBytecodeOutputDir().toString());
return includesBuilder.build();
}
protected FluentIterable<Path> getLexOutput(Iterable<Path> lexInputs) {
return FluentIterable.from(lexInputs)
.transform(
new Function<Path, Path>() {
@Override
public Path apply(Path lexInput) {
return getGeneratedSourceDir().resolve(
lexInput.getFileName().toString().replaceFirst(
OCamlCompilables.OCAML_MLL_REGEX,
OCamlCompilables.OCAML_ML));
}
});
}
protected FluentIterable<Path> getYaccOutput(Iterable<Path> yaccInputs) {
return FluentIterable.from(yaccInputs)
.transformAndConcat(
new Function<Path, Iterable<? extends Path>>() {
@Override
public Iterable<? extends Path> apply(Path yaccInput) {
String yaccFileName = yaccInput.getFileName().toString();
return ImmutableList.of(
getGeneratedSourceDir().resolve(
yaccFileName.replaceFirst(
OCamlCompilables.OCAML_MLY_REGEX,
OCamlCompilables.OCAML_ML)),
getGeneratedSourceDir().resolve(
yaccFileName.replaceFirst(
OCamlCompilables.OCAML_MLY_REGEX,
OCamlCompilables.OCAML_MLI)));
}
});
}
@Override
public RuleKey.Builder appendToRuleKey(RuleKey.Builder builder) {
return builder
.setReflectively("flags", getFlags())
.setReflectively("input", getInput())
.setReflectively("lexCompiler", getLexCompiler())
.setReflectively("ocamlBytecodeCompiler", getOcamlBytecodeCompiler())
.setReflectively("ocamlCompiler", getOcamlCompiler())
.setReflectively("ocamlDebug", getOcamlDebug())
.setReflectively("ocamlDepTool", getOcamlDepTool())
.setReflectively("yaccCompiler", getYaccCompiler());
}
public ImmutableList<String> getCCompileFlags() {
ImmutableList.Builder<String> compileFlags = ImmutableList.builder();
CxxPreprocessorInput cxxPreprocessorInput = getCxxPreprocessorInput();
for (Path headerMap : cxxPreprocessorInput.getHeaderMaps()) {
compileFlags.add("-ccopt", "-I" + headerMap.toString());
}
for (Path includes : cxxPreprocessorInput.getIncludeRoots()) {
compileFlags.add("-ccopt", "-I" + includes.toString());
}
for (Path includes : cxxPreprocessorInput.getSystemIncludeRoots()) {
compileFlags.add("-ccopt", "-isystem" + includes.toString());
}
for (String cFlag : cxxPreprocessorInput.getPreprocessorFlags().get(CxxSource.Type.C)) {
compileFlags.add("-ccopt", cFlag);
}
return compileFlags.build();
}
private static ImmutableList<String> addPrefix(String prefix, Iterable<String> flags) {
return ImmutableList.copyOf(
MoreIterables.zipAndConcat(
Iterables.cycle(prefix),
flags));
}
public ImmutableList<String> getCommonCFlags() {
ImmutableList.Builder<String> builder = ImmutableList.builder();
builder.addAll(addPrefix("-ccopt", getCFlags()));
builder.add("-ccopt",
"-isystem" +
getOCamlInteropIncludesDir()
.or(DEFAULT_OCAML_INTEROP_INCLUDE_DIR.toString()));
return builder.build();
}
public ImmutableList<String> getCommonCLinkerFlags() {
return addPrefix("-ccopt", getLdFlags());
}
public static OCamlBuildContext.Builder builder(OCamlBuckConfig config) {
return OCamlBuildContext.builder()
.setOcamlDepTool(config.getOCamlDepTool())
.setOcamlCompiler(config.getOCamlCompiler())
.setOcamlDebug(config.getOCamlDebug())
.setYaccCompiler(config.getYaccCompiler())
.setLexCompiler(config.getLexCompiler())
.setOcamlBytecodeCompiler(config.getOCamlBytecodeCompiler())
.setOCamlInteropIncludesDir(config.getOCamlInteropIncludesDir())
.setCFlags(config.getCFlags())
.setLdFlags(config.getLdFlags());
}
}
| apache-2.0 |
hsaputra/DDF | core/src/main/java/io/ddf/facades/TransformFacade.java | 3064 | package io.ddf.facades;
import io.ddf.DDF;
import io.ddf.etl.IHandleTransformations;
import io.ddf.exception.DDFException;
import java.util.ArrayList;
import java.util.List;
public class TransformFacade implements IHandleTransformations {
private DDF mDDF;
private IHandleTransformations mTransformationHandler;
{
}
public TransformFacade(DDF ddf, IHandleTransformations transformationHandler) {
this.mDDF = ddf;
this.mTransformationHandler = transformationHandler;
}
@Override
public DDF getDDF() {
return mDDF;
}
@Override
public void setDDF(DDF theDDF) {
mDDF = theDDF;
}
public IHandleTransformations getmTransformationHandler() {
return mTransformationHandler;
}
public void setmTransformationHandler(IHandleTransformations mTransformationHandler) {
this.mTransformationHandler = mTransformationHandler;
}
public DDF transformMapReduceNative(String mapFuncDef, String reduceFuncDef) {
return transformMapReduceNative(mapFuncDef, reduceFuncDef, true);
}
@Override
public DDF transformMapReduceNative(String mapFuncDef, String reduceFuncDef, boolean mapsideCombine) {
return mTransformationHandler.transformMapReduceNative(mapFuncDef, reduceFuncDef, mapsideCombine);
}
@Override
public DDF transformNativeRserve(String transformExpression) {
return mTransformationHandler.transformNativeRserve(transformExpression);
}
@Override
public DDF transformPython(String[] transformFunctions, String[] destColumns, String[][] sourceColumns) {
return mTransformationHandler.transformPython(transformFunctions, destColumns, sourceColumns);
}
@Override
public DDF transformScaleMinMax() throws DDFException {
return mTransformationHandler.transformScaleMinMax();
}
@Override
public DDF transformScaleStandard() throws DDFException {
return mTransformationHandler.transformScaleStandard();
}
@Override
public DDF transformUDF(List<String> transformExpressions, List<String> columns) throws DDFException {
return mTransformationHandler.transformUDF(transformExpressions, columns);
}
public DDF transformUDF(List<String> transformExpressions) throws DDFException {
return transformUDF(transformExpressions, null);
}
public DDF transformUDF(String transformExpression, List<String> columns) throws DDFException {
List<String> transformExpressions = new ArrayList<String>();
transformExpressions.add(transformExpression);
return mTransformationHandler.transformUDF(transformExpressions, columns);
}
/**
* Create a new column or overwrite an existing one.
*
* @param transformExpression the expression in format column=expression
* @return a DDF
* @throws DDFException
*/
public DDF transformUDF(String transformExpression) throws DDFException {
return transformUDF(transformExpression, null);
}
public DDF flattenDDF(String[] columns) throws DDFException {
return flattenDDF(columns);
}
public DDF flattenDDF() throws DDFException {
return flattenDDF();
}
}
| apache-2.0 |
Jaden-J/androidbible | AlkitabYes2/src/main/java/yuku/alkitab/yes2/section/TextSection.java | 245 | package yuku.alkitab.yes2.section;
import yuku.alkitab.yes2.section.base.SectionContent;
public class TextSection extends SectionContent {
public static final String SECTION_NAME = "text";
public TextSection() {
super(SECTION_NAME);
}
}
| apache-2.0 |
ederign/uberfire | uberfire-extensions/uberfire-layout-editor/uberfire-layout-editor-client/src/main/java/org/uberfire/ext/layout/editor/client/LayoutEditorEntryPoint.java | 977 | /*
* Copyright 2015 JBoss, by Red Hat, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.ext.layout.editor.client;
import javax.annotation.PostConstruct;
import org.jboss.errai.ioc.client.api.EntryPoint;
import org.uberfire.ext.layout.editor.client.resources.WebAppResource;
@EntryPoint
public class LayoutEditorEntryPoint {
@PostConstruct
public void init() {
WebAppResource.INSTANCE.CSS().ensureInjected();
}
} | apache-2.0 |
s-gheldd/netty | testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketSslSessionReuseTest.java | 8035 | /*
* Copyright 2015 The Netty Project
*
* The Netty Project 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 io.netty.testsuite.transport.socket;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.JdkSslClientContext;
import io.netty.handler.ssl.JdkSslContext;
import io.netty.handler.ssl.JdkSslServerContext;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSessionContext;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.cert.CertificateException;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.*;
@RunWith(Parameterized.class)
public class SocketSslSessionReuseTest extends AbstractSocketTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocketSslSessionReuseTest.class);
private static final File CERT_FILE;
private static final File KEY_FILE;
static {
SelfSignedCertificate ssc;
try {
ssc = new SelfSignedCertificate();
} catch (CertificateException e) {
throw new Error(e);
}
CERT_FILE = ssc.certificate();
KEY_FILE = ssc.privateKey();
}
@Parameters(name = "{index}: serverEngine = {0}, clientEngine = {1}")
public static Collection<Object[]> data() throws Exception {
return Collections.singletonList(new Object[] {
new JdkSslServerContext(CERT_FILE, KEY_FILE),
new JdkSslClientContext(CERT_FILE)
});
}
private final SslContext serverCtx;
private final SslContext clientCtx;
public SocketSslSessionReuseTest(SslContext serverCtx, SslContext clientCtx) {
this.serverCtx = serverCtx;
this.clientCtx = clientCtx;
}
@Test(timeout = 30000)
public void testSslSessionReuse() throws Throwable {
run();
}
public void testSslSessionReuse(ServerBootstrap sb, Bootstrap cb) throws Throwable {
final ReadAndDiscardHandler sh = new ReadAndDiscardHandler(true, true);
final ReadAndDiscardHandler ch = new ReadAndDiscardHandler(false, true);
final String[] protocols = new String[]{ "TLSv1", "TLSv1.1", "TLSv1.2" };
sb.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sch) throws Exception {
SSLEngine engine = serverCtx.newEngine(sch.alloc());
engine.setUseClientMode(false);
engine.setEnabledProtocols(protocols);
sch.pipeline().addLast(new SslHandler(engine));
sch.pipeline().addLast(sh);
}
});
final Channel sc = sb.bind().sync().channel();
cb.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sch) throws Exception {
InetSocketAddress serverAddr = (InetSocketAddress) sc.localAddress();
SSLEngine engine = clientCtx.newEngine(sch.alloc(), serverAddr.getHostString(), serverAddr.getPort());
engine.setUseClientMode(true);
engine.setEnabledProtocols(protocols);
sch.pipeline().addLast(new SslHandler(engine));
sch.pipeline().addLast(ch);
}
});
try {
SSLSessionContext clientSessionCtx = ((JdkSslContext) clientCtx).sessionContext();
ByteBuf msg = Unpooled.wrappedBuffer(new byte[] { 0xa, 0xb, 0xc, 0xd }, 0, 4);
Channel cc = cb.connect().sync().channel();
cc.writeAndFlush(msg).sync();
cc.closeFuture().sync();
rethrowHandlerExceptions(sh, ch);
Set<String> sessions = sessionIdSet(clientSessionCtx.getIds());
msg = Unpooled.wrappedBuffer(new byte[] { 0xa, 0xb, 0xc, 0xd }, 0, 4);
cc = cb.connect().sync().channel();
cc.writeAndFlush(msg).sync();
cc.closeFuture().sync();
assertEquals("Expected no new sessions", sessions, sessionIdSet(clientSessionCtx.getIds()));
rethrowHandlerExceptions(sh, ch);
} finally {
sc.close().awaitUninterruptibly();
}
}
private static void rethrowHandlerExceptions(ReadAndDiscardHandler sh, ReadAndDiscardHandler ch) throws Throwable {
if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
throw sh.exception.get();
}
if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
throw ch.exception.get();
}
if (sh.exception.get() != null) {
throw sh.exception.get();
}
if (ch.exception.get() != null) {
throw ch.exception.get();
}
}
private static Set<String> sessionIdSet(Enumeration<byte[]> sessionIds) {
Set<String> idSet = new HashSet<String>();
byte[] id;
while (sessionIds.hasMoreElements()) {
id = sessionIds.nextElement();
idSet.add(ByteBufUtil.hexDump(Unpooled.wrappedBuffer(id)));
}
return idSet;
}
@Sharable
private static class ReadAndDiscardHandler extends SimpleChannelInboundHandler<ByteBuf> {
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
private final boolean server;
private final boolean autoRead;
ReadAndDiscardHandler(boolean server, boolean autoRead) {
this.server = server;
this.autoRead = autoRead;
}
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
byte[] actual = new byte[in.readableBytes()];
in.readBytes(actual);
ctx.close();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
try {
ctx.flush();
} finally {
if (!autoRead) {
ctx.read();
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
Throwable cause) throws Exception {
if (logger.isWarnEnabled()) {
logger.warn(
"Unexpected exception from the " +
(server? "server" : "client") + " side", cause);
}
exception.compareAndSet(null, cause);
ctx.close();
}
}
}
| apache-2.0 |
Kobee1203/jcrom | src/test/java/org/jcrom/invalidobject/InvalidEntity.java | 1778 | /**
* This file is part of the JCROM project.
* Copyright (C) 2008-2015 - All rights reserved.
* Authors: Olafur Gauti Gudmundsson, Nicolas Dos Santos
*
* 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.jcrom.invalidobject;
import java.util.List;
import org.jcrom.annotations.JcrChildNode;
import org.jcrom.annotations.JcrName;
import org.jcrom.annotations.JcrPath;
import org.jcrom.annotations.JcrProperty;
/**
*
* @author Olafur Gauti Gudmundsson
* @author Nicolas Dos Santos
*/
public class InvalidEntity {
public InvalidEntity() {
}
@JcrPath
private String path;
@JcrName
private String name;
@JcrProperty
private String body;
@JcrProperty
private float number; // float properties is not supported!
@JcrChildNode
private List children; // List is not parameterized, and therefore not valid
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
| apache-2.0 |
tangjilv/news-project | XCL-Charts-demo/src/com/demo/xclcharts/view/BarChart07View_left.java | 4696 | package com.demo.xclcharts.view;
import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.List;
import org.xclcharts.chart.BarChart;
import org.xclcharts.chart.BarData;
import org.xclcharts.chart.CustomLineData;
import org.xclcharts.common.IFormatterTextCallBack;
import org.xclcharts.renderer.XEnum;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
public class BarChart07View_left extends GraphicalView {
private String TAG = "BarChart07View_left";
private BarChart chart = new BarChart();
//轴数据源
private List<String> chartLabels = new LinkedList<String>();
private List<BarData> chartData = new LinkedList<BarData>();
private List<CustomLineData> mCustomLineDataset = new LinkedList<CustomLineData>();
public BarChart07View_left(Context context) {
super(context);
// TODO Auto-generated constructor stub
initView();
}
public BarChart07View_left(Context context, AttributeSet attrs){
super(context, attrs);
initView();
}
public BarChart07View_left(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
private void initView()
{
chartLabels();
chartDataSet();
chartDesireLines();
chartRender();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
//图所占范围大小
chart.setChartRange(w,h);
}
private void chartRender()
{
try {
//标题
chart.setTitle("柱形图左右移动演示");
chart.addSubtitle("(XCL-Charts Demo)");
chart.setTitleAlign(XEnum.ChartTitleAlign.LEFT);
//数据源
chart.setDataSource(chartData);
chart.setCategories(chartLabels);
chart.setCustomLines(mCustomLineDataset);
//图例
chart.getAxisTitle().setLeftAxisTitle("参考成年男性标准值");
//数据轴
chart.getDataAxis().setAxisMax(40);
chart.getDataAxis().setAxisMin(0);
chart.getDataAxis().setAxisSteps(5);
//指隔多少个轴刻度(即细刻度)后为主刻度
chart.getDataAxis().setDetailModeSteps(2);
//定义数据轴标签显示格式
chart.getDataAxis().setLabelFormatter(new IFormatterTextCallBack(){
@Override
public String textFormatter(String value) {
// TODO Auto-generated method stub
Double tmp = Double.parseDouble(value);
DecimalFormat df=new DecimalFormat("#0");
String label = df.format(tmp).toString();
return (label);
}
});
//隐藏Key
chart.getPlotLegend().hideLegend();
chart.getCategoryAxis().setVisible(false);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void chartDataSet()
{
//标签对应的柱形数据集
List<Double> dataSeriesA= new LinkedList<Double>();
//依数据值确定对应的柱形颜色.
List<Integer> dataColorA= new LinkedList<Integer>();
dataSeriesA.add(0d);
dataColorA.add((int)Color.RED);
//此地的颜色为Key值颜色及柱形的默认颜色
BarData BarDataA = new BarData("",dataSeriesA,dataColorA,
(int)Color.rgb(53, 169, 239));
chartData.add(BarDataA);
}
private void chartLabels()
{
for(Integer i=1;i<5;i++)
{
chartLabels.add(Integer.toString(i));
}
}
/**
* 期望线/分界线
*/
private void chartDesireLines()
{
CustomLineData cl = new CustomLineData("适中",18.5d,(int)Color.rgb(77, 184, 73),3);
cl.setLabelHorizontalPostion(XEnum.LabelAlign.LEFT);
cl.hideLine();
mCustomLineDataset.add(cl);
}
@Override
public void render(Canvas canvas) {
try{
//设置图表大小
chart.setChartRange(0,0, //10f, 10f,
this.getLayoutParams().width - 10,
this.getLayoutParams().height - 10);
//top,bottom,左右两图要一致,留70px空间用于显示左轴
chart.setPadding(70,120,0, 180); //70是轴所点总宽度,在右边轴绘图时,偏移这个宽度就对好了
chart.render(canvas);
} catch (Exception e){
Log.e(TAG, e.toString());
}
}
@Override
public void onDraw(Canvas canvas){
//绘制
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return false;
}
}
| apache-2.0 |
objectiser/camel | components/camel-zookeeper/src/main/java/org/apache/camel/component/zookeeper/cloud/ZooKeeperServiceDiscovery.java | 5286 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.zookeeper.cloud;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.cloud.ServiceDefinition;
import org.apache.camel.component.zookeeper.ZooKeeperCuratorConfiguration;
import org.apache.camel.component.zookeeper.ZooKeeperCuratorHelper;
import org.apache.camel.impl.cloud.DefaultServiceDefinition;
import org.apache.camel.impl.cloud.DefaultServiceDiscovery;
import org.apache.camel.util.ObjectHelper;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.codehaus.jackson.map.annotate.JsonRootName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ZooKeeperServiceDiscovery extends DefaultServiceDiscovery {
private static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperServiceDiscovery.class);
private final ZooKeeperCuratorConfiguration configuration;
private final boolean managedInstance;
private CuratorFramework curator;
private ServiceDiscovery<MetaData> serviceDiscovery;
public ZooKeeperServiceDiscovery(ZooKeeperCuratorConfiguration configuration) {
this.configuration = configuration;
this.curator = configuration.getCuratorFramework();
this.managedInstance = Objects.isNull(curator);
}
// *********************************************
// Lifecycle
// *********************************************
@Override
protected void doStart() throws Exception {
if (curator == null) {
// Validation
ObjectHelper.notNull(getCamelContext(), "Camel Context");
ObjectHelper.notNull(configuration.getBasePath(), "ZooKeeper base path");
LOGGER.debug("Starting ZooKeeper Curator with namespace '{}', nodes: '{}'",
configuration.getNamespace(),
String.join(",", configuration.getNodes())
);
curator = ZooKeeperCuratorHelper.createCurator(configuration);
curator.start();
}
if (serviceDiscovery == null) {
// Validation
ObjectHelper.notNull(configuration.getBasePath(), "ZooKeeper base path");
LOGGER.debug("Starting ZooKeeper ServiceDiscoveryBuilder with base path '{}'",
configuration.getBasePath()
);
serviceDiscovery = ZooKeeperCuratorHelper.createServiceDiscovery(configuration, curator, MetaData.class);
serviceDiscovery.start();
}
super.doStart();
}
@Override
protected void doStop() throws Exception {
super.doStop();
if (serviceDiscovery != null) {
try {
serviceDiscovery.close();
} catch (Exception e) {
LOGGER.warn("Error closing Curator ServiceDiscovery", e);
}
}
if (curator != null && managedInstance) {
curator.close();
}
}
// *********************************************
// Implementation
// *********************************************
@Override
public List<ServiceDefinition> getServices(String name) {
if (serviceDiscovery == null) {
return Collections.emptyList();
}
try {
return serviceDiscovery.queryForInstances(name).stream()
.map(si -> {
Map<String, String> meta = new HashMap<>();
ObjectHelper.ifNotEmpty(si.getPayload(), meta::putAll);
meta.putIfAbsent(ServiceDefinition.SERVICE_META_NAME, si.getName());
meta.putIfAbsent(ServiceDefinition.SERVICE_META_ID, si.getId());
return new DefaultServiceDefinition(
si.getName(),
si.getAddress(),
si.getSslPort() != null ? si.getSslPort() : si.getPort(),
meta);
})
.collect(Collectors.toList());
} catch (Exception e) {
throw new RuntimeCamelException(e);
}
}
// *********************************************
// Helpers
// *********************************************
@JsonRootName("meta")
public static final class MetaData extends HashMap<String, String> {
}
}
| apache-2.0 |
tiarebalbi/spring-boot | spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootJar.java | 6008 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.gradle.tasks.bundling;
import java.io.File;
import java.util.Collections;
import java.util.concurrent.Callable;
import org.gradle.api.Action;
import org.gradle.api.file.CopySpec;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.FileCopyDetails;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.file.copy.CopyAction;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.bundling.Jar;
/**
* A custom {@link Jar} task that produces a Spring Boot executable jar.
*
* @author Andy Wilkinson
* @since 2.0.0
*/
public class BootJar extends Jar implements BootArchive {
private final BootArchiveSupport support = new BootArchiveSupport("org.springframework.boot.loader.JarLauncher",
this::resolveZipCompression);
private final CopySpec bootInf;
private String mainClassName;
private FileCollection classpath;
/**
* Creates a new {@code BootJar} task.
*/
public BootJar() {
this.bootInf = getProject().copySpec().into("BOOT-INF");
getMainSpec().with(this.bootInf);
this.bootInf.into("classes", classpathFiles(File::isDirectory));
this.bootInf.into("lib", classpathFiles(File::isFile));
this.bootInf.filesMatching("module-info.class",
(details) -> details.setRelativePath(details.getRelativeSourcePath()));
getRootSpec().eachFile((details) -> {
String pathString = details.getRelativePath().getPathString();
if (pathString.startsWith("BOOT-INF/lib/") && !this.support.isZip(details.getFile())) {
details.exclude();
}
});
}
private Action<CopySpec> classpathFiles(Spec<File> filter) {
return (copySpec) -> copySpec.from((Callable<Iterable<File>>) () -> (this.classpath != null)
? this.classpath.filter(filter) : Collections.emptyList());
}
@Override
public void copy() {
this.support.configureManifest(this, getMainClassName(), "BOOT-INF/classes/", "BOOT-INF/lib/");
super.copy();
}
@Override
protected CopyAction createCopyAction() {
return this.support.createCopyAction(this);
}
@Override
public String getMainClassName() {
if (this.mainClassName == null) {
String manifestStartClass = (String) getManifest().getAttributes().get("Start-Class");
if (manifestStartClass != null) {
setMainClassName(manifestStartClass);
}
}
return this.mainClassName;
}
@Override
public void setMainClassName(String mainClassName) {
this.mainClassName = mainClassName;
}
@Override
public void requiresUnpack(String... patterns) {
this.support.requiresUnpack(patterns);
}
@Override
public void requiresUnpack(Spec<FileTreeElement> spec) {
this.support.requiresUnpack(spec);
}
@Override
public LaunchScriptConfiguration getLaunchScript() {
return this.support.getLaunchScript();
}
@Override
public void launchScript() {
enableLaunchScriptIfNecessary();
}
@Override
public void launchScript(Action<LaunchScriptConfiguration> action) {
action.execute(enableLaunchScriptIfNecessary());
}
@Override
public FileCollection getClasspath() {
return this.classpath;
}
@Override
public void classpath(Object... classpath) {
FileCollection existingClasspath = this.classpath;
this.classpath = getProject().files((existingClasspath != null) ? existingClasspath : Collections.emptyList(),
classpath);
}
@Override
public void setClasspath(Object classpath) {
this.classpath = getProject().files(classpath);
}
@Override
public void setClasspath(FileCollection classpath) {
this.classpath = getProject().files(classpath);
}
@Override
public boolean isExcludeDevtools() {
return this.support.isExcludeDevtools();
}
@Override
public void setExcludeDevtools(boolean excludeDevtools) {
this.support.setExcludeDevtools(excludeDevtools);
}
/**
* Returns a {@code CopySpec} that can be used to add content to the {@code BOOT-INF}
* directory of the jar.
* @return a {@code CopySpec} for {@code BOOT-INF}
* @since 2.0.3
*/
@Internal
public CopySpec getBootInf() {
CopySpec child = getProject().copySpec();
this.bootInf.with(child);
return child;
}
/**
* Calls the given {@code action} to add content to the {@code BOOT-INF} directory of
* the jar.
* @param action the {@code Action} to call
* @return the {@code CopySpec} for {@code BOOT-INF} that was passed to the
* {@code Action}
* @since 2.0.3
*/
public CopySpec bootInf(Action<CopySpec> action) {
CopySpec bootInf = getBootInf();
action.execute(bootInf);
return bootInf;
}
/**
* Returns the {@link ZipCompression} that should be used when adding the file
* represented by the given {@code details} to the jar.
* <p>
* By default, any file in {@code BOOT-INF/lib/} is stored and all other files are
* deflated.
* @param details the details
* @return the compression to use
*/
protected ZipCompression resolveZipCompression(FileCopyDetails details) {
if (details.getRelativePath().getPathString().startsWith("BOOT-INF/lib/")) {
return ZipCompression.STORED;
}
return ZipCompression.DEFLATED;
}
private LaunchScriptConfiguration enableLaunchScriptIfNecessary() {
LaunchScriptConfiguration launchScript = this.support.getLaunchScript();
if (launchScript == null) {
launchScript = new LaunchScriptConfiguration(this);
this.support.setLaunchScript(launchScript);
}
return launchScript;
}
}
| apache-2.0 |
john9x/jdbi | core/src/main/java/org/jdbi/v3/core/statement/CallableStatementMapper.java | 862 | /*
* 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.jdbi.v3.core.statement;
import java.sql.CallableStatement;
import java.sql.SQLException;
/**
* Map an {@code OUT} parameter in a callable statement to a result type.
*/
public interface CallableStatementMapper {
Object map(int position, CallableStatement stmt) throws SQLException;
}
| apache-2.0 |
jxblum/spring-boot | spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurerIntegrationTests.java | 5800 | /*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.autoconfigure.metrics;
import java.util.Map;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.instrument.composite.CompositeMeterRegistry;
import org.junit.jupiter.api.Test;
import org.slf4j.impl.StaticLoggerBinder;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.actuate.autoconfigure.metrics.export.atlas.AtlasMetricsExportAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.export.jmx.JmxMetricsExportAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.export.prometheus.PrometheusMetricsExportAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.test.MetricsRun;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link MeterRegistryConfigurer}.
*
* @author Jon Schneider
*/
class MeterRegistryConfigurerIntegrationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.with(MetricsRun.limitedTo(AtlasMetricsExportAutoConfiguration.class,
PrometheusMetricsExportAutoConfiguration.class))
.withConfiguration(AutoConfigurations.of(JvmMetricsAutoConfiguration.class));
@Test
void binderMetricsAreSearchableFromTheComposite() {
this.contextRunner.run((context) -> {
CompositeMeterRegistry composite = context.getBean(CompositeMeterRegistry.class);
composite.get("jvm.memory.used").gauge();
context.getBeansOfType(MeterRegistry.class)
.forEach((name, registry) -> registry.get("jvm.memory.used").gauge());
});
}
@Test
void customizersAreAppliedBeforeBindersAreCreated() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(MetricsAutoConfiguration.class,
SimpleMetricsExportAutoConfiguration.class))
.withUserConfiguration(TestConfiguration.class).run((context) -> {
});
}
@Test
void counterIsIncrementedOncePerEventWithoutCompositeMeterRegistry() {
new ApplicationContextRunner().with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class))
.withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)).run((context) -> {
Logger logger = ((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory())
.getLogger("test-logger");
logger.error("Error.");
Map<String, MeterRegistry> registriesByName = context.getBeansOfType(MeterRegistry.class);
assertThat(registriesByName).hasSize(1);
MeterRegistry registry = registriesByName.values().iterator().next();
assertThat(registry.get("logback.events").tag("level", "error").counter().count()).isEqualTo(1);
});
}
@Test
void counterIsIncrementedOncePerEventWithCompositeMeterRegistry() {
new ApplicationContextRunner()
.with(MetricsRun.limitedTo(JmxMetricsExportAutoConfiguration.class,
PrometheusMetricsExportAutoConfiguration.class))
.withConfiguration(AutoConfigurations.of(LogbackMetricsAutoConfiguration.class)).run((context) -> {
Logger logger = ((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory())
.getLogger("test-logger");
logger.error("Error.");
Map<String, MeterRegistry> registriesByName = context.getBeansOfType(MeterRegistry.class);
assertThat(registriesByName).hasSize(3);
registriesByName.forEach((name,
registry) -> assertThat(
registry.get("logback.events").tag("level", "error").counter().count())
.isEqualTo(1));
});
}
@Configuration(proxyBeanMethods = false)
static class TestConfiguration {
@Bean
MeterBinder testBinder(Alpha thing) {
return (registry) -> {
};
}
@Bean
MeterRegistryCustomizer<?> testCustomizer() {
return (registry) -> registry.config().commonTags("testTag", "testValue");
}
@Bean
Alpha alpha() {
return new Alpha();
}
@Bean
Bravo bravo(Alpha alpha) {
return new Bravo(alpha);
}
@Bean
static BeanPostProcessor testPostProcessor(ApplicationContext context) {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Bravo) {
MeterRegistry meterRegistry = context.getBean(MeterRegistry.class);
meterRegistry.gauge("test", 1);
System.out.println(meterRegistry.find("test").gauge().getId().getTags());
}
return bean;
}
};
}
}
static class Alpha {
}
static class Bravo {
Bravo(Alpha alpha) {
}
}
}
| apache-2.0 |
SomeFire/ignite | modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/impl/igfs/HadoopIgfsStreamEventListener.java | 1351 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.hadoop.impl.igfs;
import org.apache.ignite.IgniteCheckedException;
/**
* IGFS input stream event listener.
*/
public interface HadoopIgfsStreamEventListener {
/**
* Callback invoked when the stream is being closed.
*
* @throws IgniteCheckedException If failed.
*/
public void onClose() throws IgniteCheckedException;
/**
* Callback invoked when remote error occurs.
*
* @param errMsg Error message.
*/
public void onError(String errMsg);
}
| apache-2.0 |
timgifford/tiles | tiles-core/src/main/java/org/apache/tiles/definition/FactoryNotFoundException.java | 1613 | /*
* $Id$
*
* 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.tiles.definition;
/**
* Exception thrown when definitions impl is not found.
*
* @version $Rev$ $Date$
*/
public class FactoryNotFoundException extends DefinitionsFactoryException {
/**
* Constructor.
*/
public FactoryNotFoundException() {
super();
}
/**
* Constructor.
*
* @param msg Message.
*/
public FactoryNotFoundException(String msg) {
super(msg);
}
/**
* Constructor.
*
* @param message Message.
* @param e Cause.
*/
public FactoryNotFoundException(String message, Throwable e) {
super(message, e);
}
/**
* Constructor.
*
* @param e Cause.
*/
public FactoryNotFoundException(Throwable e) {
super(e);
}
}
| apache-2.0 |
ddebrunner/quarks | utils/metrics/src/test/java/quarks/test/metrics/MetricsOffTest.java | 304 | /*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015,2016
*/
package quarks.test.metrics;
import org.junit.Ignore;
// No registered Metrics service
@Ignore("abstract, provides common tests for concrete implementations")
public abstract class MetricsOffTest extends MetricsBaseTest {
}
| apache-2.0 |
qobel/esoguproject | spring-framework/spring-context/src/main/java/org/springframework/context/annotation/ImportRegistry.java | 934 | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.annotation;
import org.springframework.core.type.AnnotationMetadata;
/**
* @author Juergen Hoeller
* @author Phil Webb
*/
interface ImportRegistry {
AnnotationMetadata getImportingClassFor(String importedClass);
void removeImportingClassFor(String importedClass);
}
| apache-2.0 |
gingerwizard/elasticsearch | client/rest-high-level/src/main/java/org/elasticsearch/client/security/ClearPrivilegesCacheResponse.java | 1976 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.security;
import org.elasticsearch.client.NodesResponseHeader;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.List;
/**
* The response object that will be returned when clearing the privileges cache
*/
public final class ClearPrivilegesCacheResponse extends SecurityNodesResponse {
@SuppressWarnings("unchecked")
private static final ConstructingObjectParser<ClearPrivilegesCacheResponse, Void> PARSER =
new ConstructingObjectParser<>("clear_privileges_cache_response", false,
args -> new ClearPrivilegesCacheResponse((List<Node>)args[0], (NodesResponseHeader) args[1], (String) args[2]));
static {
SecurityNodesResponse.declareCommonNodesResponseParsing(PARSER);
}
public ClearPrivilegesCacheResponse(List<Node> nodes, NodesResponseHeader header, String clusterName) {
super(nodes, header, clusterName);
}
public static ClearPrivilegesCacheResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
}
| apache-2.0 |
afinka77/ignite | modules/yardstick/src/main/java/org/apache/ignite/yardstick/cache/dml/IgniteSqlDeleteFilteredBenchmark.java | 3067 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.yardstick.cache.dml;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.yardstick.cache.IgniteCacheAbstractBenchmark;
import org.apache.ignite.yardstick.cache.model.Person;
import org.yardstickframework.BenchmarkConfiguration;
import static org.yardstickframework.BenchmarkUtils.println;
/**
* Ignite benchmark that performs put and SQL DELETE operations.
*/
public class IgniteSqlDeleteFilteredBenchmark extends IgniteCacheAbstractBenchmark<Integer, Object> {
/** */
private AtomicInteger putCnt = new AtomicInteger();
/** */
private AtomicInteger delCnt = new AtomicInteger();
/** */
private AtomicInteger delItemsCnt = new AtomicInteger();
/** {@inheritDoc} */
@Override public void setUp(BenchmarkConfiguration cfg) throws Exception {
super.setUp(cfg);
}
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
if (rnd.nextBoolean()) {
double salary = rnd.nextDouble() * args.range() * 1000;
double maxSalary = salary + 1000;
int res = (Integer) cache().query(new SqlFieldsQuery("delete from Person where salary >= ? and salary <= ?")
.setArgs(salary, maxSalary)).getAll().get(0).get(0);
delItemsCnt.getAndAdd(res);
delCnt.getAndIncrement();
}
else {
int i = rnd.nextInt(args.range());
cache.put(i, new Person(i, "firstName" + i, "lastName" + i, i * 1000));
putCnt.getAndIncrement();
}
return true;
}
/** {@inheritDoc} */
@Override protected IgniteCache<Integer, Object> cache() {
return ignite().cache("query");
}
/** {@inheritDoc} */
@Override public void tearDown() throws Exception {
println(cfg, "Finished SQL DELETE query benchmark [putCnt=" + putCnt.get() + ", delCnt=" + delCnt.get() +
", delItemsCnt=" + delItemsCnt.get() + ']');
super.tearDown();
}
}
| apache-2.0 |