hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
0a1f38f65f5fd5134d422503f3d32eaed7b3ef17
11,788
/* * Copyright 2002-2016 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.ldap.server; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.directory.server.core.DefaultDirectoryService; import org.apache.directory.server.core.authn.AuthenticationInterceptor; import org.apache.directory.server.core.entry.ServerEntry; import org.apache.directory.server.core.exception.ExceptionInterceptor; import org.apache.directory.server.core.interceptor.Interceptor; import org.apache.directory.server.core.normalization.NormalizationInterceptor; import org.apache.directory.server.core.operational.OperationalAttributeInterceptor; import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition; import org.apache.directory.server.core.referral.ReferralInterceptor; import org.apache.directory.server.core.subtree.SubentryInterceptor; import org.apache.directory.server.ldap.LdapServer; import org.apache.directory.server.protocol.shared.store.LdifFileLoader; import org.apache.directory.server.protocol.shared.transport.TcpTransport; import org.apache.directory.shared.ldap.exception.LdapNameNotFoundException; import org.apache.directory.shared.ldap.name.LdapDN; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.Lifecycle; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.util.Assert; /** * Provides lifecycle services for the embedded apacheDS server defined by the supplied * configuration. Used by {@code LdapServerBeanDefinitionParser}. An instance will be * stored in the application context for each embedded server instance. It will start the * server when the context is initialized and shut it down when it is closed. It is * intended for temporary embedded use and will not retain changes across start/stop * boundaries. The working directory is deleted on shutdown. * * <p> * If used repeatedly in a single JVM process with the same configuration (for example, * when repeatedly loading an application context during testing), it's important that the * application context is closed to allow the bean to be disposed of and the server * shutdown prior to attempting to start it again. * <p> * This class is intended for testing and internal security namespace use, only, and is not * considered part of the framework's public API. * * @author Luke Taylor * @author Rob Winch * @author Gunnar Hillert */ public class ApacheDSContainer implements InitializingBean, DisposableBean, Lifecycle, ApplicationContextAware { private final Log logger = LogFactory.getLog(getClass()); final DefaultDirectoryService service; LdapServer server; private ApplicationContext ctxt; private File workingDir; private boolean running; private final String ldifResources; private final JdbmPartition partition; private final String root; private int port = 53389; private boolean ldapOverSslEnabled; private File keyStoreFile; private String certificatePassord; public ApacheDSContainer(String root, String ldifs) throws Exception { this.ldifResources = ldifs; service = new DefaultDirectoryService(); List<Interceptor> list = new ArrayList<>(); list.add(new NormalizationInterceptor()); list.add(new AuthenticationInterceptor()); list.add(new ReferralInterceptor()); // list.add( new AciAuthorizationInterceptor() ); // list.add( new DefaultAuthorizationInterceptor() ); list.add(new ExceptionInterceptor()); // list.add( new ChangeLogInterceptor() ); list.add(new OperationalAttributeInterceptor()); // list.add( new SchemaInterceptor() ); list.add(new SubentryInterceptor()); // list.add( new CollectiveAttributeInterceptor() ); // list.add( new EventInterceptor() ); // list.add( new TriggerInterceptor() ); // list.add( new JournalInterceptor() ); service.setInterceptors(list); partition = new JdbmPartition(); partition.setId("rootPartition"); partition.setSuffix(root); this.root = root; service.addPartition(partition); service.setExitVmOnShutdown(false); service.setShutdownHookEnabled(false); service.getChangeLog().setEnabled(false); service.setDenormalizeOpAttrsEnabled(true); } public void afterPropertiesSet() throws Exception { if (workingDir == null) { String apacheWorkDir = System.getProperty("apacheDSWorkDir"); if (apacheWorkDir == null) { apacheWorkDir = createTempDirectory("apacheds-spring-security-"); } setWorkingDirectory(new File(apacheWorkDir)); } if (this.ldapOverSslEnabled && this.keyStoreFile == null) { throw new IllegalArgumentException("When LdapOverSsl is enabled, the keyStoreFile property must be set."); } server = new LdapServer(); server.setDirectoryService(service); // AbstractLdapIntegrationTests assume IPv4, so we specify the same here TcpTransport transport = new TcpTransport(port); if (ldapOverSslEnabled) { transport.setEnableSSL(true); server.setKeystoreFile(this.keyStoreFile.getAbsolutePath()); server.setCertificatePassword(this.certificatePassord); } server.setTransports(transport); start(); } public void destroy() throws Exception { stop(); } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ctxt = applicationContext; } public void setWorkingDirectory(File workingDir) { Assert.notNull(workingDir, "workingDir cannot be null"); logger.info("Setting working directory for LDAP_PROVIDER: " + workingDir.getAbsolutePath()); if (workingDir.exists()) { throw new IllegalArgumentException( "The specified working directory '" + workingDir.getAbsolutePath() + "' already exists. Another directory service instance may be using it or it may be from a " + " previous unclean shutdown. Please confirm and delete it or configure a different " + "working directory"); } this.workingDir = workingDir; service.setWorkingDirectory(workingDir); } public void setPort(int port) { this.port = port; } /** * If set to {@code true} will enable LDAP over SSL (LDAPs). If set to {@code true} * {@link ApacheDSContainer#setCertificatePassord(String)} must be set as well. * * @param ldapOverSslEnabled If not set, will default to false */ public void setLdapOverSslEnabled(boolean ldapOverSslEnabled) { this.ldapOverSslEnabled = ldapOverSslEnabled; } /** * The keyStore must not be null and must be a valid file. Will set the keyStore file on the underlying {@link LdapServer}. * @param keyStoreFile Mandatory if LDAPs is enabled */ public void setKeyStoreFile(File keyStoreFile) { Assert.notNull(keyStoreFile, "The keyStoreFile must not be null."); Assert.isTrue(keyStoreFile.isFile(), "The keyStoreFile must be a file."); this.keyStoreFile = keyStoreFile; } /** * Will set the certificate password on the underlying {@link LdapServer}. * * @param certificatePassord May be null */ public void setCertificatePassord(String certificatePassord) { this.certificatePassord = certificatePassord; } public DefaultDirectoryService getService() { return service; } public void start() { if (isRunning()) { return; } if (service.isStarted()) { throw new IllegalStateException("DirectoryService is already running."); } logger.info("Starting directory server..."); try { service.startup(); server.start(); } catch (Exception e) { throw new RuntimeException("Server startup failed", e); } try { service.getAdminSession().lookup(partition.getSuffixDn()); } catch (LdapNameNotFoundException e) { try { LdapDN dn = new LdapDN(root); Assert.isTrue(root.startsWith("dc="), "root must start with dc="); String dc = root.substring(3, root.indexOf(',')); ServerEntry entry = service.newEntry(dn); entry.add("objectClass", "top", "domain", "extensibleObject"); entry.add("dc", dc); service.getAdminSession().add(entry); } catch (Exception e1) { logger.error("Failed to create dc entry", e1); } } catch (Exception e) { logger.error("Lookup failed", e); } running = true; try { importLdifs(); } catch (Exception e) { throw new RuntimeException("Failed to import LDIF file(s)", e); } } public void stop() { if (!isRunning()) { return; } logger.info("Shutting down directory server ..."); try { server.stop(); service.shutdown(); } catch (Exception e) { logger.error("Shutdown failed", e); return; } running = false; if (workingDir.exists()) { logger.info("Deleting working directory " + workingDir.getAbsolutePath()); deleteDir(workingDir); } } private void importLdifs() throws Exception { // Import any ldif files Resource[] ldifs; if (ctxt == null) { // Not running within an app context ldifs = new PathMatchingResourcePatternResolver().getResources(ldifResources); } else { ldifs = ctxt.getResources(ldifResources); } // Note that we can't just import using the ServerContext returned // from starting Apache DS, apparently because of the long-running issue // DIRSERVER-169. // We need a standard context. // DirContext dirContext = contextSource.getReadWriteContext(); if (ldifs == null || ldifs.length == 0) { return; } if (ldifs.length == 1) { String ldifFile; try { ldifFile = ldifs[0].getFile().getAbsolutePath(); } catch (IOException e) { ldifFile = ldifs[0].getURI().toString(); } logger.info("Loading LDIF file: " + ldifFile); LdifFileLoader loader = new LdifFileLoader(service.getAdminSession(), new File(ldifFile), null, getClass().getClassLoader()); loader.execute(); } else { throw new IllegalArgumentException( "More than one LDIF resource found with the supplied pattern:" + ldifResources + " Got " + Arrays.toString(ldifs)); } } private String createTempDirectory(String prefix) throws IOException { String parentTempDir = System.getProperty("java.io.tmpdir"); String fileNamePrefix = prefix + System.nanoTime(); String fileName = fileNamePrefix; for (int i = 0; i < 1000; i++) { File tempDir = new File(parentTempDir, fileName); if (!tempDir.exists()) { return tempDir.getAbsolutePath(); } fileName = fileNamePrefix + "~" + i; } throw new IOException("Failed to create a temporary directory for file at " + new File(parentTempDir, fileNamePrefix)); } private boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (String child : children) { boolean success = deleteDir(new File(dir, child)); if (!success) { return false; } } } return dir.delete(); } public boolean isRunning() { return running; } }
32.032609
124
0.736766
69ba2fb589ededb079c4a7fda1050fce37de7541
445
package com.baidu.amis.validation; /** * 仿照 javax.validation 力度命名,但多了个字段名 */ public class ConstraintViolation { // 字段名 private String name; // 违反信息 private String message; public ConstraintViolation(String name, String message) { this.name = name; this.message = message; } public String getName() { return name; } public String getMessage() { return message; } }
15.892857
61
0.613483
813ff2867f41280a74cd4448af34d31a5624652c
436
package top.itning.eurekaprovider2; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableEurekaClient public class Eurekaprovider2Application { public static void main(String[] args) { SpringApplication.run(Eurekaprovider2Application.class, args); } }
29.066667
70
0.823394
f8bb2b90c7671fbce4e31e52f6273b91ccb4687c
18,091
package br.com.ariane.fiora.app; import br.com.ariane.fiora.modelo.Usuario; import javax.swing.JOptionPane; public class FrmAlterarUsuario extends javax.swing.JFrame { Usuario usuario = new Usuario(); public FrmAlterarUsuario() { initComponents(); //Torna os campos de alteração invisíveis até que seja efetuada a procura tfNome.setEnabled(false); tfFuncao.setEnabled(false); pwSenha.setEnabled(false); btnAlterar.setEnabled(false); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); pwSenha = new javax.swing.JPasswordField(); jLabel2 = new javax.swing.JLabel(); lbLogin = new javax.swing.JLabel(); btnAlterar = new javax.swing.JButton(); btnSair = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); tfNome = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); tfFuncao = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); tfLogin = new javax.swing.JTextField(); btnProcurar = new javax.swing.JButton(); btnLimparTela = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Alterar Usuário"); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Informações de Login")); jLabel3.setText("Senha:"); pwSenha.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pwSenhaActionPerformed(evt); } }); jLabel2.setText("Login:"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(pwSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE) .addComponent(lbLogin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbLogin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(pwSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(14, Short.MAX_VALUE)) ); btnAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/ariane/fiora/images/editar.png"))); // NOI18N btnAlterar.setText("Alterar"); btnAlterar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAlterarActionPerformed(evt); } }); btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/ariane/fiora/images/sair.png"))); // NOI18N btnSair.setText("Sair"); btnSair.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSairActionPerformed(evt); } }); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Informações do Usuário")); jLabel1.setText("Nome:"); jLabel5.setText("Função:"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel5) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfNome, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE) .addComponent(tfFuncao)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(tfNome, 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.BASELINE) .addComponent(jLabel5) .addComponent(tfFuncao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jLabel4.setText("Digite o login:"); btnProcurar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/ariane/fiora/images/procurar.png"))); // NOI18N btnProcurar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnProcurarActionPerformed(evt); } }); btnLimparTela.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/ariane/fiora/images/limpar.png"))); // NOI18N btnLimparTela.setText("Limpar Tela"); btnLimparTela.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLimparTelaActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(btnAlterar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSair) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnLimparTela)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(tfLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnProcurar, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tfLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(23, 23, 23)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(btnProcurar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAlterar) .addComponent(btnSair) .addComponent(btnLimparTela)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed try { //Valida campos obrigatórios if ((tfNome.getText().isEmpty()) || (tfFuncao.getText().isEmpty()) || (pwSenha.getPassword() == null)) { JOptionPane.showMessageDialog(this, "Preencha todos os campos!", "Aviso", JOptionPane.WARNING_MESSAGE); } else { usuario.setNome(tfNome.getText()); usuario.setFuncao(tfFuncao.getText()); usuario.setSenha(Integer.parseInt(String.valueOf(pwSenha.getPassword()))); //Adiciona os dados no banco de dados usuario.alterarUsuario(usuario); JOptionPane.showMessageDialog(this, "Usuário alterado!", "Alteração", JOptionPane.INFORMATION_MESSAGE); this.dispose(); } } catch (NumberFormatException e) { JOptionPane.showMessageDialog(this, "Digite a senha somente com números!"); } }//GEN-LAST:event_btnAlterarActionPerformed private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed this.dispose(); }//GEN-LAST:event_btnSairActionPerformed private void pwSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pwSenhaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pwSenhaActionPerformed private void btnProcurarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProcurarActionPerformed //Busca o usuário para fazer a alteração if (tfLogin.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Digite um nome para a busca", "Atenção", JOptionPane.WARNING_MESSAGE); } else { usuario = usuario.buscarUsuario(tfLogin.getText()); try { if (usuario == null) { JOptionPane.showMessageDialog(this, "Não há usuário cadastrado com esse login!\nTente novamente.", "Erro", JOptionPane.ERROR_MESSAGE); usuario = new Usuario(); } else { //Torna os campos de alteração visíveis tfNome.setEnabled(true); tfFuncao.setEnabled(true); pwSenha.setEnabled(true); btnAlterar.setEnabled(true); //Exibe os dados já cadastrados nos campos de texto tfNome.setText(usuario.getNome()); tfFuncao.setText(usuario.getFuncao()); pwSenha.setText(Integer.toString(usuario.getSenha())); lbLogin.setText(usuario.getLogin()); //Torna os campos da procura invisívels btnProcurar.setEnabled(false); tfLogin.setText(""); tfLogin.setEnabled(false); } } catch (NullPointerException ne) { JOptionPane.showMessageDialog(this, "Erro"); } } }//GEN-LAST:event_btnProcurarActionPerformed private void btnLimparTelaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparTelaActionPerformed //Apaga todos os dados dos campos preenchidos e retorna para a procura tfNome.setEnabled(false); tfNome.setText(""); tfFuncao.setEnabled(false); tfFuncao.setText(""); pwSenha.setEnabled(false); pwSenha.setText(""); btnAlterar.setEnabled(false); lbLogin.setText(""); tfLogin.setEnabled(true); tfLogin.setText(""); btnProcurar.setEnabled(true); }//GEN-LAST:event_btnLimparTelaActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FrmAlterarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FrmAlterarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FrmAlterarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FrmAlterarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FrmAlterarUsuario().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAlterar; private javax.swing.JButton btnLimparTela; private javax.swing.JButton btnProcurar; private javax.swing.JButton btnSair; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JLabel lbLogin; private javax.swing.JPasswordField pwSenha; private javax.swing.JTextField tfFuncao; private javax.swing.JTextField tfLogin; private javax.swing.JTextField tfNome; // End of variables declaration//GEN-END:variables }
53.365782
169
0.648168
e398123c057965781fcdd105ab5b4f4dc1923fb6
250
package com.github.instagram4j.instagram4j.models.direct.item; import com.github.instagram4j.instagram4j.models.media.thread.ThreadMedia; import lombok.Data; @Data public class ThreadMediaItem extends ThreadItem { private ThreadMedia media; }
22.727273
74
0.82
c8ee30a4b627c5834bbb183bcca3148fd01be183
12,949
package il.ac.technion.ie.experiments.service; import com.google.common.collect.Multimap; import com.univocity.parsers.csv.CsvParser; import com.univocity.parsers.csv.CsvWriter; import com.univocity.parsers.csv.CsvWriterSettings; import il.ac.technion.ie.canopy.model.DuplicateReductionContext; import il.ac.technion.ie.experiments.builder.FebrlBlockBuilder; import il.ac.technion.ie.experiments.builder.iBlockBuilder; import il.ac.technion.ie.experiments.exception.SizeNotEqualException; import il.ac.technion.ie.experiments.model.BlockResults; import il.ac.technion.ie.experiments.model.BlockWithData; import il.ac.technion.ie.experiments.model.CompareAlgorithmResults; import il.ac.technion.ie.experiments.parsers.DatasetParser; import il.ac.technion.ie.model.Record; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * Created by I062070 on 22/08/2015. */ public class ParsingService { public static final String RANKED_VALUE = "Ranked Value"; public static final String MRR = "MRR"; public static final String THRESHOLD = "Threshold"; public static final String NORM_RANKED_VALUE = "Norm Ranked Value"; public static final String NORM_MRR = "Norm MRR"; private static final String MILLER_RANKED_VALUE = "Miller Ranked Value"; private static final String MILLER_MRR_VALUE = "Miller MRR Value"; public static final String FEBERL_PARAMETER = "Feberl parameter"; private static final String DATASET_NAME = "Dataset Name"; private static final String[] HEADERS_SINGLE_BLOCK_SET = {DATASET_NAME, "Missing Real Representatives", "Power of Real Reap - Recall", "Wisdom of the crowd - Precision - Precision", "duplicatesRemoved", "Duplicates Real Representatives", "Average block size", "Average number of blocks", "baseline Duration (mil)", "bcbp Duration (mil)"}; private static final String[] HEADERS_BASELINE_AND_ALG = {DATASET_NAME, "True Reps % - Baseline", "True Reps % - BCBP", "Recall - Baseline", "Recall - BCBP", "Precision - Baseline", "Precision - BCBP", "Missing Real Representatives - Baseline", "Missing Real Representatives - BCBP", "Duplicates Real Representatives", "New added ground truth reps by BCBP", "removed ground truth reps by BCBP", "Duplicates Removed", "% pulled records, rep should remain", "% pulled records, rep should NOT remain", "Average block size", "Average number of blocks", "Baseline Duration (mil)", "BCBP Duration (mil)"}; private DatasetParser dataParser; private iBlockBuilder blockBuilder; public ParsingService() { this.dataParser = new DatasetParser(); blockBuilder = new FebrlBlockBuilder(); } public List<BlockWithData> parseDataset(String pathToFile) { List<BlockWithData> blocksWithData = new ArrayList<>(); CsvParser parser = dataParser.getParserForFile(pathToFile); String[] fields = parser.parseNext(); if (fields != null) { List<String> fieldsNames = new ArrayList<>(Arrays.asList(fields)); blocksWithData = blockBuilder.build(parser, fieldsNames); } return blocksWithData; } public void writeBlocks(List<BlockWithData> blocks, String pathToFile) { CsvWriter csvWriter = dataParser.preparOutputFile(pathToFile); if (csvWriter != null) { // Write the record headers of this file List<String> fieldsNames = getBlockFieldsNames(blocks); fieldsNames.add("Probability"); csvWriter.writeHeaders(fieldsNames); // Let's write the rows one by one for (BlockWithData block : blocks) { for (Record record : block.getMembers()) { for (String recordEntry : record.getEntries()) { csvWriter.writeValue(recordEntry); } csvWriter.writeValues(block.getMemberProbability(record)); csvWriter.writeValuesToRow(); } } // Here we just tell the writer to write everything and close the given output Writer instance. csvWriter.close(); } } private List<String> getBlockFieldsNames(List<BlockWithData> blocks) { if (blocks != null && !blocks.isEmpty()) { final BlockWithData blockWithData = blocks.get(0); return blockWithData.getFieldNames(); } return null; } public void writeExperimentsMeasurements(IMeasurements measurements, File tempFile) throws SizeNotEqualException { CsvWriter csvWriter = dataParser.preparOutputFile(tempFile); csvWriter.writeHeaders(THRESHOLD, RANKED_VALUE, MRR, NORM_RANKED_VALUE, NORM_MRR, MILLER_RANKED_VALUE, MILLER_MRR_VALUE); List<Double> mrrValues = measurements.getMrrValuesSortedByThreshold(); List<Double> rankedValues = measurements.getRankedValuesSortedByThreshold(); List<Double> thresholds = measurements.getThresholdSorted(); List<Double> normalizedRankedValues = measurements.getNormalizedRankedValuesSortedByThreshold(); List<Double> normalizedMRRValues = measurements.getNormalizedMRRValuesSortedByThreshold(); assertSize(measurements); Double millerRankedValue = getMillerRankedValue(rankedValues); Double millerMRRValue = getMillerMRRValue(mrrValues); for (int i = 1; i < thresholds.size(); i++) { csvWriter.writeValue(MRR, mrrValues.get(i)); csvWriter.writeValue(THRESHOLD, thresholds.get(i)); csvWriter.writeValue(RANKED_VALUE, rankedValues.get(i)); csvWriter.writeValue(NORM_RANKED_VALUE, normalizedRankedValues.get(i)); csvWriter.writeValue(NORM_MRR, normalizedMRRValues.get(i)); csvWriter.writeValue(MILLER_RANKED_VALUE, millerRankedValue); csvWriter.writeValue(MILLER_MRR_VALUE, millerMRRValue); csvWriter.writeValuesToRow(); } csvWriter.close(); } private Double getMillerMRRValue(List<Double> mrrValues) { if (!mrrValues.isEmpty()) { return mrrValues.get(0); } else { return null; } } private Double getMillerRankedValue(List<Double> rankedValues) { if (!rankedValues.isEmpty()) { return rankedValues.get(0); } else { return null; } } private void assertSize(IMeasurements measurements) throws SizeNotEqualException { List<Double> mrrValues = measurements.getMrrValuesSortedByThreshold(); List<Double> rankedValues = measurements.getRankedValuesSortedByThreshold(); List<Double> thresholds = measurements.getThresholdSorted(); List<Double> normalizedRankedValues = measurements.getNormalizedRankedValuesSortedByThreshold(); List<Double> normalizedMRRValues = measurements.getNormalizedMRRValuesSortedByThreshold(); if ((thresholds.size() != rankedValues.size()) || (thresholds.size() != mrrValues.size()) || (thresholds.size() != normalizedRankedValues.size()) || (thresholds.size() != normalizedMRRValues.size())) { throw new SizeNotEqualException(String.format("The size of %s, %s and %s is not equal", RANKED_VALUE, MRR, THRESHOLD)); } } public void writeExperimentsMeasurements(DuplicateReductionContext duplicateReductionContext, File file) { CsvWriter csvWriter = dataParser.preparOutputFile(file); csvWriter.writeHeaders("Missing Real Representatives", "Power of Real Reap - Recall", "Wisdom of the crowd - Precision", "duplicatesRemoved"); writeDuplicateReductionContext(duplicateReductionContext, csvWriter); csvWriter.close(); } private void writeDuplicateReductionContext(DuplicateReductionContext duplicateReductionContext, CsvWriter csvWriter) { csvWriter.writeValue("Missing Real Representatives", duplicateReductionContext.getRepresentationDiff()); csvWriter.writeValue("Duplicates Real Representatives", duplicateReductionContext.getDuplicatesRealRepresentatives()); csvWriter.writeValue("duplicatesRemoved", duplicateReductionContext.getDuplicatesRemoved()); csvWriter.writeValue("Power of Real Reap - Recall", duplicateReductionContext.getRepresentativesPower()); csvWriter.writeValue("Wisdom of the crowd - Precision", duplicateReductionContext.getWisdomCrowds()); csvWriter.writeValue("Average number of blocks", duplicateReductionContext.getNumberOfDirtyBlocks()); csvWriter.writeValue("Average block size", duplicateReductionContext.getAverageBlockSize()); csvWriter.writeValuesToRow(); } public void writeExperimentsMeasurements(Map<Integer, DuplicateReductionContext> map, File expResults) { CsvWriter csvWriter = dataParser.preparOutputFile(expResults); csvWriter.writeHeaders(FEBERL_PARAMETER, "Missing Real Representatives", "Power of Real Reap - Recall", "Wisdom of the crowd - Precision", "duplicatesRemoved", "Duplicates Real Representatives", "Average block size", "Average number of blocks"); for (Map.Entry<Integer, DuplicateReductionContext> entry : map.entrySet()) { csvWriter.writeValue(FEBERL_PARAMETER, entry.getKey()); this.writeDuplicateReductionContext(entry.getValue(), csvWriter); } csvWriter.close(); } public void writeExperimentsMeasurements(Multimap<String, DuplicateReductionContext> results, File expResults) { CsvWriter csvWriter = dataParser.preparOutputFile(expResults); csvWriter.writeHeaders(HEADERS_SINGLE_BLOCK_SET); for (Map.Entry<String, DuplicateReductionContext> entry : results.entries()) { csvWriter.writeValue(DATASET_NAME, entry.getKey()); DuplicateReductionContext reductionContext = entry.getValue(); this.writeDuplicateReductionContext(reductionContext, csvWriter); csvWriter.writeValue("baseline Duration (mil)", reductionContext.getBaselineDuration()); csvWriter.writeValue("bcbp Duration (mil)", reductionContext.getBcbpDuration()); } csvWriter.close(); } public void writeComparisonExperimentsMeasurements(Multimap<String, DuplicateReductionContext> results, File expResults) { CsvWriterSettings settings = new CsvWriterSettings(); settings.setHeaders(HEADERS_BASELINE_AND_ALG); settings.selectFields(HEADERS_BASELINE_AND_ALG); CsvWriter csvWriter = dataParser.preparOutputFile(expResults, settings); csvWriter.writeHeaders(); for (Map.Entry<String, DuplicateReductionContext> entry : results.entries()) { csvWriter.writeRow(buildComparisonRow(entry)); } csvWriter.close(); } private List<Object> buildComparisonRow(Map.Entry<String, DuplicateReductionContext> entry) { DuplicateReductionContext reductionContext = entry.getValue(); BlockResults baselineResults = reductionContext.getBaselineResults(); BlockResults bcbpResults = reductionContext.getBcbpResults(); CompareAlgorithmResults compareAlgsResults = reductionContext.getCompareAlgsResults(); List<Object> rowContent = new ArrayList<>(); rowContent.add(entry.getKey()); //TrueRepsPercentage rowContent.add(baselineResults.getTrueRepsPercentage()); rowContent.add(bcbpResults.getTrueRepsPercentage()); //Recall rowContent.add(baselineResults.getRecall()); rowContent.add(bcbpResults.getRecall()); //Precision rowContent.add(baselineResults.getPrecision()); rowContent.add(bcbpResults.getPrecision()); //MRR rowContent.add(baselineResults.getMrr()); rowContent.add(bcbpResults.getMrr()); //DRR rowContent.add(compareAlgsResults.getDrr()); rowContent.add(compareAlgsResults.getNewAddedReps()); rowContent.add(compareAlgsResults.getRemovedGroundTruthReps()); rowContent.add(reductionContext.getDuplicatesRemoved()); //% pulled records by representatives that should and should not remain rowContent.add(reductionContext.getBlockShouldRemainPulled()); rowContent.add(reductionContext.getBlockShouldNotRemainPulled()); rowContent.add(reductionContext.getNumberOfDirtyBlocks()); rowContent.add(reductionContext.getAverageBlockSize()); rowContent.add(reductionContext.getBaselineDuration()); rowContent.add(reductionContext.getBcbpDuration()); return rowContent; } }
47.959259
131
0.693104
1267e0f792e8d2c3ae8a5b76895f1d1150f65468
27
package com.simast.service;
27
27
0.851852
0bce23af118f446312b8ec017750fc4020a77ef6
5,986
package com.example.test.mytest.permission; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.example.test.mytest.R; import com.example.test.mytest.util.ConstDef; import com.example.test.mytest.util.UtilPermission; import com.example.test.mytest.widget.activity.MyTestActivity; import com.example.test.mytest.widget.permission.CheckPermission; import com.example.test.mytest.widget.permission.Dlog; import com.example.test.mytest.widget.permission.PermissionListener; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by Harry on 2017. 4. 4.. */ public class PermissionGuideActivity extends AppCompatActivity { private static final int REQ_CODE_REQUEST_SETTING = 20; @BindView(R.id.permission_guide_text) TextView permissionGuideText; String[] permissions; String packageName; @Override protected void onResume() { super.onResume(); overridePendingTransition(0, 0); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.permission_guide_activity); ButterKnife.bind(this); setupFromSavedInstanceState(savedInstanceState); } private void setupFromSavedInstanceState(Bundle savedInstanceState) { if (savedInstanceState != null) { permissions = savedInstanceState.getStringArray(ConstDef.EXTRA_PERMISSIONS); packageName = savedInstanceState.getString(ConstDef.EXTRA_PACKAGE_NAME); } else { Intent intent = getIntent(); permissions = intent.getStringArrayExtra(ConstDef.EXTRA_PERMISSIONS); // packageName = intent.getStringExtra(ConstDef.EXTRA_PACKAGE_NAME); packageName = this.getPackageName(); } StringBuilder sb = new StringBuilder(); for (String permission : permissions) { sb.append(permission + "\n"); } permissionGuideText.setText(sb.toString()); } @Override public void onSaveInstanceState(Bundle outState) { outState.putStringArray(ConstDef.EXTRA_PERMISSIONS, permissions); outState.putString(ConstDef.EXTRA_PACKAGE_NAME, packageName); super.onSaveInstanceState(outState); } @OnClick(R.id.permission_guide_btn) public void onClickPermissionBtn() { checkPermission(); // super.checkPermission(permissions); } private void checkPermission() { new CheckPermission(this, permissions, new PermissionListener() { @Override public void onPermissionGranted() { Dlog.d("Granted"); setResult(RESULT_OK); PermissionGuideActivity.this.finish(); } @Override public void onPermissionDenied(ArrayList<String> deniedPermissions) { // nothing to do Dlog.d("Denied"); } @Override public void onPermissionDeniedNeedShowDialogSetting(ArrayList<String> deniedPermissions) { // showPermissionDenyDialog(); Dlog.d("Denied - regardless request Setting"); if (UtilPermission.checkSelfPermissions(PermissionGuideActivity.this, permissions).isEmpty()) { setResult(RESULT_OK); } else { // setResult(RESULT_CANCELED); showPermissionDenyDialog(); } // PermissionGuideActivity.this.finish(); } }).check(); } public void showPermissionDenyDialog() { Dlog.d(""); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.permission_need_setting)) .setCancelable(false) .setNegativeButton(getString(R.string.close), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // nothing to do } }) .setPositiveButton(getString(R.string.setting), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).setData(Uri.parse("package:" + packageName)); startActivityForResult(intent, REQ_CODE_REQUEST_SETTING); } catch (ActivityNotFoundException e) { Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS); startActivityForResult(intent, REQ_CODE_REQUEST_SETTING); } } }); builder.show(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_CODE_REQUEST_SETTING: // checkPermission(); if (UtilPermission.checkSelfPermissions(this, permissions).isEmpty()) { setResult(RESULT_OK); PermissionGuideActivity.this.finish(); // } else { // setResult(RESULT_CANCELED); // PermissionGuideActivity.this.finish(); } break; } } }
36.950617
146
0.631306
f067f4d72da63906c5906d8b3707d3559a7c2674
1,002
package com.op1.util; import com.op1.aiff.FormatVersionChunk; import com.op1.iff.types.*; public class Op1Constants { public static final Extended SAMPLE_RATE_44100 = new Extended(new byte[]{ 64, 14, -84, 68, 0, 0, 0, 0, 0, 0 }); public static final byte[] COMMON_CHUNK_DESCRIPTION = ")Signed integer (little-endian) linear PCM".getBytes(); public static final OSType APPLICATION_CHUNK_SIGNATURE = OSType.fromString("op-1"); public static final SignedShort NUM_CHANNELS_MONO = SignedShort.fromShort((short) 1); public static final SignedShort SAMPLE_SIZE_16_BIT = SignedShort.fromShort((short) 16); public static final ID ID_SOWT = ID.valueOf("sowt"); public static final FormatVersionChunk FORMAT_VERSION_CHUNK = new FormatVersionChunk.Builder() .withChunkSize(SignedLong.fromInt(4)) .withTimestamp(new UnsignedLong(new byte[]{-94, -128, 81, 64})) .build(); public static final int DRUMKIT_END = 2147483646; }
38.538462
114
0.709581
c1ad12c01feb92e37898e66f409788b12b643c27
92,028
package org.iitk.brihaspati.modules.utils; /* * @(#)QuizMetaDataXmlWriter.java * * Copyright (c) 2010-2011,2013 DEI Agra, IITK, 2017 IITK. * 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. * * Redistribution in binary form must reproducuce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ETRG OR ITS 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. * * * Contributors: DEI Agra, IITK * */ import java.util.Date; import java.io.File; import java.util.Vector; import org.xml.sax.helpers.AttributesImpl; import java.io.FileOutputStream; import org.xml.sax.Attributes; import org.xml.sax.helpers.AttributesImpl; import org.iitk.brihaspati.modules.utils.XmlWriter; import org.iitk.brihaspati.modules.utils.QuizMetaDataXmlReader; import org.iitk.brihaspati.modules.utils.QuizFileEntry; import org.iitk.brihaspati.modules.utils.FileLockUnlock; import org.iitk.brihaspati.modules.utils.BufferQuizThread; import org.apache.turbine.util.RunData; import org.apache.turbine.om.security.User; import org.apache.turbine.services.servlet.TurbineServlet; import java.io.IOException; import org.apache.commons.lang.math.Range; import org.apache.commons.lang.math.DoubleRange; import java.util.Random; import java.util.Map; /** * This class generate Xml file with attributes and values * @author <a href="mailto:noopur.here@gmail.com">Nupur Dixit</a> * @author <a href="mailto:palseema30@gmail.com">Manorama Pal</a>01Aug2013 * @author <a href="mailto:singh_jaivir@rediffmail.com">Jaivir Singh</a>03jan2013 */ public class QuizMetaDataXmlWriter { /** * This method write xml file with tags * @param fileName String */ public synchronized static void OLESRootOnly(String fileName) throws Exception { /* FileOutputStream fos=new FileOutputStream(fileName); fos.write( ("<QuizFile>\n</QuizFile>").getBytes() ); fos.close(); */ FileLockUnlock fl =new FileLockUnlock(fileName); boolean gl = fl.getlock(); if(gl) { FileOutputStream fop = new FileOutputStream(fileName); fop.write(("<QuizFile>\n</QuizFile>").getBytes()); fop.close(); fl.releaselock(); } } /** * This method append element in existing xml file * @param xmlWriter XmlWriter * @param quizId String * @param quizName String * @param maxMarks String * @param maxTime String * @param noQuestion String * @param status String * @param Filename String * @param CreationDate String * @param ModifiedDate String * @param quizMode String * @param allow String * @author <a href="mailto:noopur.here@gmail.com">Nupur Dixit</a> */ public static void appendQues_Banklist(XmlWriter xmlWriter,String quizID,String quizName,String maxMarks,String maxTime,String noQuestion,String status,String Filename,String CreationDate,String ModifiedDate,String quizMode,String allow) { AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuizID","","",StringUtil.replaceXmlSpecialCharacters(quizID)); ats.addAttribute("","QuizName","","",StringUtil.replaceXmlSpecialCharacters(quizName)); ats.addAttribute("","MaxMarks","","",StringUtil.replaceXmlSpecialCharacters(maxMarks)); ats.addAttribute("","MaxTime","","",StringUtil.replaceXmlSpecialCharacters(maxTime)); ats.addAttribute("","NumberQuestion","","",StringUtil.replaceXmlSpecialCharacters(noQuestion)); ats.addAttribute("","status","","",StringUtil.replaceXmlSpecialCharacters(status)); ats.addAttribute("","Filename","","",StringUtil.replaceXmlSpecialCharacters(Filename)); ats.addAttribute("","CreationDate","","",CreationDate); ats.addAttribute("","ModifiedDate","","",ModifiedDate); ats.addAttribute("","QuizMode","","",quizMode); ats.addAttribute("","AllowPractice","","",StringUtil.replaceXmlSpecialCharacters(allow)); xmlWriter.appendElement("Quiz",null,ats); } /** * This method append element in existing xml file * @param xmlWriter XmlWriter * @param quizid String * @param quizname String * @param max marks String * @param max time String * @param number of question String * @param status String * @param filename String * @param CreationDate String * @param ModifiedDate String * @param quizMode String * @param startDate String * @param startTime String * @param endDate String * @param endTime String * @param allow String * @param resDate String * @author <a href="mailto:noopur.here@gmail.com">Nupur Dixit</a> */ public static void appendQuiz_list(XmlWriter xmlWriter,String quizID,String quizName,String maxMarks,String maxTime,String noQuestion,String status,String Filename,String CreationDate,String ModifiedDate,String quizMode,String startDate,String startTime,String endDate,String endTime,String allow,String resDate) { AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuizID","","",StringUtil.replaceXmlSpecialCharacters(quizID)); ats.addAttribute("","QuizName","","",StringUtil.replaceXmlSpecialCharacters(quizName)); ats.addAttribute("","MaxMarks","","",StringUtil.replaceXmlSpecialCharacters(maxMarks)); ats.addAttribute("","MaxTime","","",StringUtil.replaceXmlSpecialCharacters(maxTime)); ats.addAttribute("","NumberQuestion","","",StringUtil.replaceXmlSpecialCharacters(noQuestion)); ats.addAttribute("","status","","",StringUtil.replaceXmlSpecialCharacters(status)); ats.addAttribute("","Filename","","",StringUtil.replaceXmlSpecialCharacters(Filename)); ats.addAttribute("","CreationDate","","",CreationDate); ats.addAttribute("","ModifiedDate","","",ModifiedDate); ats.addAttribute("","QuizMode","","",quizMode); ats.addAttribute("","ExamDate","","",StringUtil.replaceXmlSpecialCharacters(startDate)); ats.addAttribute("","StartTime","","",StringUtil.replaceXmlSpecialCharacters(startTime)); ats.addAttribute("","ExpiryDate","","",StringUtil.replaceXmlSpecialCharacters(endDate)); ats.addAttribute("","EndTime","","",StringUtil.replaceXmlSpecialCharacters(endTime)); ats.addAttribute("","AllowPractice","","",StringUtil.replaceXmlSpecialCharacters(allow)); ats.addAttribute("","ResultDate","","",resDate); xmlWriter.appendElement("Quiz",null,ats); } public static void update_QuizList(XmlWriter xmlWriter,String quizID,String quizName,String maxMarks,String maxTime,String noQuestion,String status,String Filename,String CreationDate,String modifiedDate, String quizMode,int seq,String allowPractice,String ExamDate,String startTime,String ExpiryDate,String endTime,String resDate) { try{ AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuizID","","",StringUtil.replaceXmlSpecialCharacters(quizID)); ats.addAttribute("","QuizName","","",StringUtil.replaceXmlSpecialCharacters(quizName)); ats.addAttribute("","MaxMarks","","",StringUtil.replaceXmlSpecialCharacters(maxMarks)); ats.addAttribute("","MaxTime","","",StringUtil.replaceXmlSpecialCharacters(maxTime)); ats.addAttribute("","NumberQuestion","","",StringUtil.replaceXmlSpecialCharacters(noQuestion)); ats.addAttribute("","status","","",StringUtil.replaceXmlSpecialCharacters(status)); ats.addAttribute("","Filename","","",StringUtil.replaceXmlSpecialCharacters(Filename)); ats.addAttribute("","CreationDate","","",CreationDate); ats.addAttribute("","QuizMode","","",quizMode); ats.addAttribute("","ModifiedDate","","",modifiedDate); ats.addAttribute("","ExamDate","","",ExamDate); ats.addAttribute("","StartTime","","",startTime); ats.addAttribute("","ExpiryDate","","",ExpiryDate); ats.addAttribute("","EndTime","","",endTime); ats.addAttribute("","AllowPractice","","",allowPractice); ats.addAttribute("","ResultDate","","",resDate); xmlWriter.changeAttributes("Quiz",ats,seq); } catch(Exception e){ ErrorDumpUtil.ErrorLog("The exception in Quizxmlwriterutil [XmlWriter update quiz list]::"+e); } } /** * This method update file element in existing xml file with sequence number * and all updated variables values * @param file path String * @param xmlfileName String * @param seqno Integer * @param quizid String * @param max marks String * @param max time String * @param number of question String * @param ModifiedDate String * @author <a href="mailto:noopur.here@gmail.com">Nupur Dixit</a> */ public static XmlWriter Update_QuizList(String filePath,String xmlfile, int seq, String quizID,String maxMarks,String maxTime,String noQuestion,String modifiedDate) { XmlWriter xmlWriter=null; try{ QuizMetaDataXmlReader quizMetaData=new QuizMetaDataXmlReader(filePath+"/"+xmlfile); Vector v=quizMetaData.getQuiz_Detail(quizID); xmlWriter=new XmlWriter(filePath+"/"+xmlfile); for(int i=0;i<v.size();i++) { String quizName=((QuizFileEntry)v.get(i)).getQuizName(); String status=((QuizFileEntry)v.get(i)).getQuizStatus(); String Filename=((QuizFileEntry)v.get(i)).getQuizFileName(); String CreationDate=((QuizFileEntry)v.get(i)).getCreationDate(); String quizMode = ((QuizFileEntry)v.get(i)).getQuizMode(); String allowPractice = ((QuizFileEntry)v.get(i)).getAllowPractice(); String ExamDate=((QuizFileEntry) v.elementAt(i)).getExamDate(); String StartTime=((QuizFileEntry) v.elementAt(i)).getStartTime(); String ExpiryDate=((QuizFileEntry) v.elementAt(i)).getExpiryDate(); String EndTime=((QuizFileEntry) v.elementAt(i)).getEndTime(); String resDate=((QuizFileEntry) v.elementAt(i)).getResDate(); if(ExamDate!=null && StartTime!=null && ExpiryDate!=null && EndTime!=null && resDate!=null){ update_QuizList(xmlWriter,quizID,quizName,maxMarks,maxTime,noQuestion,status,Filename,CreationDate,modifiedDate,quizMode,seq,allowPractice,ExamDate,StartTime,ExpiryDate,EndTime,resDate); } /*else update_QuizList(xmlWriter,quizID,quizName,maxMarks,maxTime,noQuestion,status,Filename,CreationDate,modifiedDate,quizMode,seq,allowPractice);*/ } } catch(Exception e){ ErrorDumpUtil.ErrorLog("The exception in Quizxmlwriterutil [XmlWriter update_quizlist]::"+e); } return xmlWriter; } /** * This method update file element in existing quizid_questionSetting.xml file with sequence number * and all updated variables values * @param file path String * @param xmlfileName String * @param seqno Integer * @param topicName String * @param question type String * @param question Level String * @param marks per question String * @param number of question String * @param ID of row String * @author <a href="mailto:noopur.here@gmail.com">Nupur Dixit</a> */ public static XmlWriter Update_QuizQuestionSetting(String filePath,String xmlfile, int seq, String topicName,String queType,String queLevel,String queMarks,String noQuestion,String ID) { XmlWriter xmlWriter=null; try{ xmlWriter=new XmlWriter(filePath+"/"+xmlfile); AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","TopicName","","",StringUtil.replaceXmlSpecialCharacters(topicName)); ats.addAttribute("","QuestionType","","",StringUtil.replaceXmlSpecialCharacters(queType)); ats.addAttribute("","QuestionLevel","","",StringUtil.replaceXmlSpecialCharacters(queLevel)); ats.addAttribute("","QuestionMarks","","",StringUtil.replaceXmlSpecialCharacters(queMarks)); ats.addAttribute("","QuestionNumber","","",StringUtil.replaceXmlSpecialCharacters(noQuestion)); ats.addAttribute("","ID","","",StringUtil.replaceXmlSpecialCharacters(ID)); xmlWriter.changeAttributes("QuizQuestions",ats,seq); } catch(Exception e){ //ErrorDumpUtil.ErrorLog("The exception in Quizxmlwriterutil [XmlWriter update_quizlist]::"+e); } return xmlWriter; } /** * This method append element in existing xml (quizid_questionSetting.xml) file * @param xmlWriter XmlWriter * @param topic name String * @param type of question String * @param level of question String * @param marks per question String * @param number of question String * @author <a href="mailto:aayushi.sr@gmail.com">Aayushi</a> */ public static void appendRandomQuizlist(XmlWriter xmlWriter,String topicName,String type,String level,String marks, String numberQuestion, String id) { AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","TopicName","","",StringUtil.replaceXmlSpecialCharacters(topicName)); ats.addAttribute("","QuestionType","","",StringUtil.replaceXmlSpecialCharacters(type)); ats.addAttribute("","QuestionLevel","","",StringUtil.replaceXmlSpecialCharacters(level)); ats.addAttribute("","QuestionMarks","","",StringUtil.replaceXmlSpecialCharacters(marks)); ats.addAttribute("","QuestionNumber","","",StringUtil.replaceXmlSpecialCharacters(numberQuestion)); ats.addAttribute("","ID","","",StringUtil.replaceXmlSpecialCharacters(id)); xmlWriter.appendElement("QuizQuestions",null,ats); } /** * This method append element in existing xml (quizid_question.xml) file * @param xmlWriter XmlWriter * @param questionID String * @param question String * @param option1 String * @param option2 String * @param option3 String * @param option4 String * @param Answer String * @param file name String * @param type of question String * @param CreationDate String * @author <a href="mailto:aayushi.sr@gmail.com">Aayushi</a> */ public static void appendRandomQuizSettinglist(XmlWriter xmlWriter,String questionID,String question,String option1, String option2, String option3, String option4, String answer,String min,String max,String fileName, String typeName, String marks, String creationDate) { //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter---appendRandomQuizSettinglist-----Line 283--typeName-->"+typeName); AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuestionID","","",StringUtil.replaceXmlSpecialCharacters(questionID)); ats.addAttribute("","Question","","",StringUtil.replaceXmlSpecialCharacters(question)); if(typeName.equals("mcq")) { ats.addAttribute("","OptionA","","",StringUtil.replaceXmlSpecialCharacters(option1)); ats.addAttribute("","OptionB","","",StringUtil.replaceXmlSpecialCharacters(option2)); ats.addAttribute("","OptionC","","",StringUtil.replaceXmlSpecialCharacters(option3)); ats.addAttribute("","OptionD","","",StringUtil.replaceXmlSpecialCharacters(option4)); } if(typeName.equals("sart")) { ats.addAttribute("","Min","","",StringUtil.replaceXmlSpecialCharacters(min)); ats.addAttribute("","Max","","",StringUtil.replaceXmlSpecialCharacters(max)); } else ats.addAttribute("","Answer","","",StringUtil.replaceXmlSpecialCharacters(answer)); ats.addAttribute("","QuestionMarks","","",StringUtil.replaceXmlSpecialCharacters(marks)); ats.addAttribute("","FileName","","",StringUtil.replaceXmlSpecialCharacters(fileName)); ats.addAttribute("","CreationDate","","",StringUtil.replaceXmlSpecialCharacters(creationDate)); //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter---appendRandomQuizSettinglist-----Line 308--typeName-->"+typeName); xmlWriter.appendElement("QuizQuestions",null,ats); } /** This method is responsible for writing temporary xml file for final question list * @param filepath String path to quizid_temp_question.xml * @param filename String quizid_temp_question.xml * @param questionID String ID of question * @param question String question * @param options String option1, option2, option3, option4 * @param answer String answer of question * @param Marks String marks per question * @param filename String filename of question * @param question type String type(mcq,tft,sat,lat) * @param CreationDate String * @author nupur dixit */ //public static void xmlwriteFinalQuestion(String filePath,String quizXmlPath,String questionID,String question,String option1,String option2, String option3, String option4, String answer,String marksPerQuestion,String fileName,String typeName, String CreationDate,String min,String max){ public static void xmlwriteFinalQuestion(String filePath,String quizXmlPath,String questionID,String question,String option1,String option2, String option3, String option4, String answer,String marksPerQuestion,String fileName,String typeName, String CreationDate,String min,String max){ try{ XmlWriter xmlWriter=null; File Tempxmls=new File(filePath+"/"+quizXmlPath); // ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter.xmlwriteFinalQuestion-----Tempxmls--->"+Tempxmls+"---typeName--->"+typeName); QuizMetaDataXmlReader quizMetaData=null; /** *Checking for xml file presence *@see QuizMetaDataXmlWriter in Util. */ if(!Tempxmls.exists()) { // ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter.xmlwriteFinalQuestion-----Tempxmls--->"+Tempxmls); QuizMetaDataXmlWriter.OLESRootOnly(Tempxmls.getAbsolutePath()); } xmlWriter=new XmlWriter(filePath+"/"+quizXmlPath); xmlWriter=RandomQuizWriteTempxml(filePath,quizXmlPath,typeName); //QuizMetaDataXmlWriter.appendRandomQuizSettinglist(xmlWriter,questionID,question,option1,option2,option3,option4,answer,fileName,typeName,marksPerQuestion,CreationDate,min,max); // ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter.xmlwriteFinalQuestion-----341--->"); QuizMetaDataXmlWriter.appendRandomQuizSettinglist(xmlWriter,questionID,question,option1,option2,option3,option4,answer,min,max,fileName,typeName,marksPerQuestion,CreationDate); xmlWriter.writeXmlFile(); }//try catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in util method:xmlwriteFinalQuestion !!"+e); // data.setMessage("See ExceptionLog !! " ); }//catch }//method end /** * This method update file element in existing quizid_question.xml file with sequence number * and all updated variables values * @param file path String * @param xmlfileName String * @param seqno Integer * @param questionid String * @param question String * @param option1 String * @param option2 String * @param option3 String * @param option4 String * @param answer String * @param marks per question String * @param file name String * @author <a href="mailto:aayushi.sr@gmail.com">Aayushi</a> */ public static XmlWriter UpdateQuizQuestion(String filePath,String xmlfile, int seq, String questionID, String question, String option1, String option2, String option3, String option4, String answer, String questionMarks, String fileName) { XmlWriter xmlWriter=null; try{ xmlWriter=new XmlWriter(filePath+"/"+xmlfile); AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuestionID","","",StringUtil.replaceXmlSpecialCharacters(questionID)); ats.addAttribute("","Question","","",StringUtil.replaceXmlSpecialCharacters(question)); ats.addAttribute("","OptionA","","",StringUtil.replaceXmlSpecialCharacters(option1)); ats.addAttribute("","OptionB","","",StringUtil.replaceXmlSpecialCharacters(option2)); ats.addAttribute("","OptionC","","",StringUtil.replaceXmlSpecialCharacters(option3)); ats.addAttribute("","OptionD","","",StringUtil.replaceXmlSpecialCharacters(option4)); ats.addAttribute("","Answer","","",StringUtil.replaceXmlSpecialCharacters(answer)); ats.addAttribute("","QuestionMarks","","",StringUtil.replaceXmlSpecialCharacters(questionMarks)); ats.addAttribute("","FileName","","",StringUtil.replaceXmlSpecialCharacters(fileName)); xmlWriter.changeAttributes("QuizQuestions",ats,seq-1); } catch(Exception e){ ErrorDumpUtil.ErrorLog("The exception in Quizxmlwriterutil [XmlWriter update_quizquestionlist]::"+e); } return xmlWriter; } /** * This method update file element in existing quiz.xml file with sequence number * and all updated variables values * @param file path String * @param quizPath String * @param seqno Integer * @param quizid String * @param start date String * @param start time String * @param end date String * @param end time String * @param allow practice String * @author <a href="mailto:aayushi.sr@gmail.com">Aayushi</a> */ public static XmlWriter announceQuiz(String filePath,String quizPath,int seq,String quizID,String startDate,String startTime,String endDate,String endTime,String resDate) { XmlWriter xmlWriter=null; try{ //if(seq!= -1){ QuizMetaDataXmlReader quizMetaData=new QuizMetaDataXmlReader(filePath+"/"+quizPath); Vector v=quizMetaData.getQuiz_Detail(quizID); xmlWriter=new XmlWriter(filePath+"/"+quizPath); for(int i=0;i<v.size();i++) { String quizid=((QuizFileEntry)v.get(i)).getQuizID(); String quizName=((QuizFileEntry)v.get(i)).getQuizName(); String maxMarks=((QuizFileEntry)v.get(i)).getMaxMarks(); String maxTime=((QuizFileEntry)v.get(i)).getMaxTime(); String noQuestion=((QuizFileEntry)v.get(i)).getnoQuestion(); String status=((QuizFileEntry)v.get(i)).getQuizStatus(); String fileName=((QuizFileEntry)v.get(i)).getQuizFileName(); String creationDate=((QuizFileEntry)v.get(i)).getCreationDate(); String modifiedDate=((QuizFileEntry)v.get(i)).getModifiedDate(); String quizMode = ((QuizFileEntry)v.get(i)).getQuizMode(); String allowPractice = ((QuizFileEntry)v.get(i)).getAllowPractice(); AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuizID","","",StringUtil.replaceXmlSpecialCharacters(quizID)); ats.addAttribute("","QuizName","","",quizName); ats.addAttribute("","MaxMarks","","",maxMarks); ats.addAttribute("","MaxTime","","",maxTime); ats.addAttribute("","NumberQuestion","","",noQuestion); ats.addAttribute("","status","","",status); ats.addAttribute("","Filename","","",fileName); ats.addAttribute("","CreationDate","","",creationDate); ats.addAttribute("","ModifiedDate","","",modifiedDate); ats.addAttribute("","QuizMode","","",quizMode); ats.addAttribute("","ExamDate","","",StringUtil.replaceXmlSpecialCharacters(startDate)); ats.addAttribute("","StartTime","","",StringUtil.replaceXmlSpecialCharacters(startTime)); ats.addAttribute("","ExpiryDate","","",StringUtil.replaceXmlSpecialCharacters(endDate)); ats.addAttribute("","EndTime","","",StringUtil.replaceXmlSpecialCharacters(endTime)); ats.addAttribute("","AllowPractice","","",allowPractice); if(!(resDate.equals("$Res_year-$Res_month-$Res_day"))){ ats.addAttribute("","ResultDate","","",resDate); } xmlWriter=QuizMetaDataXmlWriter.QuizXml(filePath,quizPath); xmlWriter.writeXmlFile(); xmlWriter.changeAttributes("Quiz",ats,seq); xmlWriter.writeXmlFile(); } } catch(Exception e){ ErrorDumpUtil.ErrorLog("The exception in Quizxmlwriterutil [XmlWriter announceQuiz]::"+e); } return xmlWriter; } /** This method is responsible for writing student'a answer in userid.xml file for general quiz * @param filepath String path to userid.xml * @param filename String userid.xml * @param data RunData * @author nupur dixit */ public static void xmlwriteFinalAnswer(String filePath,String quizXmlPath,RunData data) { try { User user=data.getUser(); String courseid=(String)user.getTemp("course_id"); String quizID=data.getParameters().getString("quizID",""); String quesID=data.getParameters().getString("quesID",""); String fileName=data.getParameters().getString("fileName",""); String studentAnswer=data.getParameters().getString("finalAnswer",""); String quesType=data.getParameters().getString("quesType",""); //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----StudentAns--->"+studentAnswer); String awardedMarks = ""; String markPerQues = data.getParameters().getString("markPerQues",""); XmlWriter xmlWriter=null; File Tempxmls=new File(filePath+"/"+quizXmlPath); QuizMetaDataXmlReader quizMetaData=null; Vector<QuizFileEntry> questionVector = (Vector)user.getTemp("questionvector"); String question,realAnswer,option1,option2,option3,option4,minr,maxr; question=realAnswer=option1=option2=option3=option4=""; double stud_Answer = 0.0d, min_r = 0.0d, max_r = 0.0d; if(questionVector!=null) { for(int i=0;i<questionVector.size();i++) { String quesid=((QuizFileEntry) questionVector.elementAt(i)).getQuestionID(); String filename=((QuizFileEntry) questionVector.elementAt(i)).getFileName(); if((quesID.equals(quesid)) && (fileName.equals(filename)) ) { question = ((QuizFileEntry) questionVector.elementAt(i)).getQuestion(); if(quesType.equalsIgnoreCase("sart")) { minr = ((QuizFileEntry) questionVector.elementAt(i)).getMin(); maxr = ((QuizFileEntry) questionVector.elementAt(i)).getMax(); min_r = Double.parseDouble(minr); max_r = Double.parseDouble(maxr); //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----StudentAns1--->"); try { stud_Answer = Double.parseDouble(studentAnswer); } catch(NumberFormatException ex) { //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----StudentAns2--->"+stud_Answer); } //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----StudentAns3--->"+studentAnswer); } else { realAnswer = ((QuizFileEntry) questionVector.elementAt(i)).getAnswer(); } if(quesType.equalsIgnoreCase("mcq")) { option1=((QuizFileEntry) questionVector.elementAt(i)).getOption1(); option2=((QuizFileEntry) questionVector.elementAt(i)).getOption2(); option3=((QuizFileEntry) questionVector.elementAt(i)).getOption3(); option4=((QuizFileEntry) questionVector.elementAt(i)).getOption4(); if(studentAnswer.equals(option1)) studentAnswer="A"; if(studentAnswer.equals(option2)) studentAnswer="B"; if(studentAnswer.equals(option3)) studentAnswer="C"; if(studentAnswer.equals(option4)) studentAnswer="D"; } if(quesType.equalsIgnoreCase("sart")) { Range ansrange = new DoubleRange( min_r, max_r ); if( !ansrange.containsDouble(stud_Answer)) { // ErrorDumpUtil.ErrorLog("----No----"); awardedMarks = "0"; break; } else { // ErrorDumpUtil.ErrorLog("----Yes----"); awardedMarks = markPerQues; break; } } else { if(studentAnswer.equalsIgnoreCase(realAnswer)){ awardedMarks = markPerQues; break; } else{ awardedMarks = "0"; break; } } } } }//if(questionvector) boolean foundDuplicate = false; int seq=-1; /** *Checking for xml file presence *@see QuizMetaDataXmlWriter in Util. */ if(!Tempxmls.exists()) { //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----!Tempxmls.exists()-->"); //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----StudentAns-2-->"+quizXmlPath); QuizMetaDataXmlWriter.OLESRootOnly(Tempxmls.getAbsolutePath()); } else{ //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----StudentAns-3-->"+filePath); //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----StudentAns-4-->"+quizXmlPath); quizMetaData=new QuizMetaDataXmlReader(filePath+"/"+quizXmlPath); Vector finalAnswer=quizMetaData.getFinalAnswer(); if(finalAnswer!=null){ for(int i=0;i<finalAnswer.size();i++) { String quesid=((QuizFileEntry) finalAnswer.elementAt(i)).getQuestionID(); String filename=((QuizFileEntry) finalAnswer.elementAt(i)).getFileName(); //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----Tempxmls.exists()-->"); //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----filename-->"+filename); if((quesID.equals(quesid)) && (fileName.equals(filename)) ){ foundDuplicate=true; seq = i; break; } } }//end if if((foundDuplicate==true) &&(seq!=-1)){ ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----foundDuplicate==true-->"); xmlWriter=WriteinStudtAnswerxml(filePath,quizXmlPath,quesType,-1); QuizMetaDataXmlWriter.appendAnswerPractice(xmlWriter,quesID,fileName,question,studentAnswer,realAnswer,markPerQues,awardedMarks,option1,option2,option3,option4,min_r,max_r,quesType,seq);//call overload method at line 721 xmlWriter.writeXmlFile(); } }//end else //case for ist time writing in xml file. if((foundDuplicate==false )&&(seq==-1)){ ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----foundDuplicate==false-->") ; xmlWriter=new XmlWriter(filePath+"/"+quizXmlPath); // QuizMetaDataXmlWriter.appendAnswer(xmlWriter,quesID,fileName,answer,markPerQues,awardedMarks,seq); //----------------------------------modification done by seema and jaivir---------------------------// xmlWriter=WriteinStudtAnswerxml(filePath,quizXmlPath,quesType,seq); //-------------------------------------------------------------// //modify this code for writing in xml added 2 more param min and max QuizMetaDataXmlWriter.appendAnswerPractice(xmlWriter,quesID,fileName,question,studentAnswer,realAnswer,markPerQues,awardedMarks,option1,option2,option3,option4,min_r,max_r,quesType,seq);//call overload method at line 721, 14 parameter xmlWriter.writeXmlFile(); //========================this part is to add scores in final score.xml concurrently======================================== // String scoreFilePath=TurbineServlet.getRealPath("/Courses"+"/"+courseid+"/Exam/"); String scoreFilePath=TurbineServlet.getRealPath("/Courses"+"/"+courseid+"/Exam/"+quizID); //chaged by prajwal String scorePath="score.xml"; QuizMetaDataXmlWriter.xmlwriteFinalScore(scoreFilePath, scorePath, data); } //============================================================================ data.setMessage("Answer is saved successfully" ); }//try catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in Action[OLES_Quiz] method:xmlwriteQuizlist !!"+e); data.setMessage("some problem to save answer kindly See ExceptionLog !! " ); }//catch }//method end /** * This method append final answers in existing xml (userid.xml) file * @param xmlWriter XmlWriter * @param questionID String * @param file name String * @param Answer String * @param marks per question String * @param awarded marks String * @param sequence int * @author <a href="mailto:noopur.here@gmail.com">Nupur Dixit</a> */ public static void appendAnswer(XmlWriter xmlWriter,String questionID,String fileName,String answer,String markPerQues,String awardedMarks, int seq){ try{ AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuestionID","","",StringUtil.replaceXmlSpecialCharacters(questionID)); ats.addAttribute("","FileName","","",StringUtil.replaceXmlSpecialCharacters(fileName)); ats.addAttribute("","Answer","","",StringUtil.replaceXmlSpecialCharacters(answer)); ats.addAttribute("","QuestionMarks","","",StringUtil.replaceXmlSpecialCharacters(markPerQues)); ats.addAttribute("","AwardedMarks","","",StringUtil.replaceXmlSpecialCharacters(awardedMarks)); if(seq != -1){ xmlWriter.changeAttributes("QuizQuestions",ats,seq); } else{ xmlWriter.appendElement("QuizQuestions",null,ats); } }catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in Action[OLES_Quiz] method:xmlwriteQuizlist !!"+e); // data.setMessage("some problem to save answer kindly See ExceptionLog !! " ); } } /** * This method append final answers in existing xml (userid.xml) file * @param xmlWriter XmlWriter * @param questionID String * @param file name String * @param Answer String * @param marks per question String * @param awarded marks String * @param sequence int * @author <a href="mailto:noopur.here@gmail.com">Nupur Dixit</a> */ /* modified the method according to the sart type addes 2 more parameter min and max */ //14 parameter public static void appendAnswerPractice(XmlWriter xmlWriter,String questionID,String fileName,String question,String studentAnswer,String realAnswer,String markPerQues,String awardedMarks,String option1,String option2,String option3,String option4,double min,double max,String quesType, int seq){ try{ // ErrorDumpUtil.ErrorLog("---QuizMetaDataXmlWriter---appendAnswerPractice()---main"); AttributesImpl ats=new AttributesImpl(); String min_s = String.valueOf(min);//min.toString(); String max_s = String.valueOf(max);//max.toString(); ats.addAttribute("","QuestionID","","",StringUtil.replaceXmlSpecialCharacters(questionID)); ats.addAttribute("","FileName","","",StringUtil.replaceXmlSpecialCharacters(fileName)); ats.addAttribute("","Question","","",StringUtil.replaceXmlSpecialCharacters(question)); ats.addAttribute("","StudentAnswer","","",StringUtil.replaceXmlSpecialCharacters(studentAnswer)); //ats.addAttribute("","InstructorAnswer","","",StringUtil.replaceXmlSpecialCharacters(realAnswer)); ats.addAttribute("","QuestionMarks","","",StringUtil.replaceXmlSpecialCharacters(markPerQues)); if(quesType.equalsIgnoreCase("sart")){ ats.addAttribute("","Min","","",StringUtil.replaceXmlSpecialCharacters(min_s)); ats.addAttribute("","Max","","",StringUtil.replaceXmlSpecialCharacters(max_s)); } else ats.addAttribute("","InstructorAnswer","","",StringUtil.replaceXmlSpecialCharacters(realAnswer)); ats.addAttribute("","AwardedMarks","","",StringUtil.replaceXmlSpecialCharacters(awardedMarks)); /* if(quesType.equalsIgnoreCase("sart")){ ats.addAttribute("","Min","","",StringUtil.replaceXmlSpecialCharacters(min_s)); ats.addAttribute("","Max","","",StringUtil.replaceXmlSpecialCharacters(max_s)); } else ats.addAttribute("","InstructorAnswer","","",StringUtil.replaceXmlSpecialCharacters(realAnswer)); */ if(quesType.equalsIgnoreCase("mcq")){ ats.addAttribute("","OptionA","","",StringUtil.replaceXmlSpecialCharacters(option1)); ats.addAttribute("","OptionB","","",StringUtil.replaceXmlSpecialCharacters(option2)); ats.addAttribute("","OptionC","","",StringUtil.replaceXmlSpecialCharacters(option3)); ats.addAttribute("","OptionD","","",StringUtil.replaceXmlSpecialCharacters(option4)); } if(seq != -1){ xmlWriter.changeAttributes("QuizQuestions",ats,seq); } else{ xmlWriter.appendElement("QuizQuestions",null,ats); } }catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in quiz writer method :appendAnswerPractice !!"+e); // data.setMessage("some problem to save answer kindly See ExceptionLog !! " ); } } /** This method is responsible for writing final score.xml file * @param filepath String path to score.xml * @param filename String score.xml * @param RunData data * @author nupur dixit */ public static void xmlwriteFinalScore(String filePath,String quizXmlPath,RunData data){ try{ User user=data.getUser(); String uname=user.getName(); String uid=Integer.toString(UserUtil.getUID(uname)); String courseid=(String)user.getTemp("course_id"); String quizID=data.getParameters().getString("quizID",""); String remainTime = data.getParameters().getString("timerValue",""); String maxTime = data.getParameters().getString("maxTime",""); String usedTime = calcUsedTime(maxTime,remainTime); String messageFlag = data.getParameters().getString("messageFlag",""); int totalScore=0; int awardedMarks = 0; //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----filename-->"+filename); String answerFilePath=TurbineServlet.getRealPath("/Courses"+"/"+courseid+"/Exam/"+quizID+"/"); //ErrorDumpUtil.ErrorLog("answerfilepath in superman"+answerFilePath); String answerPath=uid+".xml"; File answerFile=new File(answerFilePath+"/"+answerPath); File scoreFile=new File(filePath+"/"+quizXmlPath); XmlWriter xmlWriter=null; QuizMetaDataXmlReader quizMetaData=null; if(!scoreFile.exists()) { QuizMetaDataXmlWriter.OLESRootOnly(scoreFile.getAbsolutePath()); } //==============This part is use to overwrite the content of score.xml if entries are for the same user================= QuizMetaDataXmlReader scoreData = null; scoreData=new QuizMetaDataXmlReader(filePath+"/"+quizXmlPath); int seq = -1; seq = scoreData.getSeqOfAlreadyInsertedScore(filePath,quizXmlPath,quizID,uid); //============================================ xmlWriter=new XmlWriter(filePath+"/"+quizXmlPath); if(!answerFile.exists()) { //BufferThread.storage(quizID,uid,totalScore,usedTime,seq); xmlWriter=WriteinScorexml(filePath,quizXmlPath); QuizMetaDataXmlWriter.writeScore(xmlWriter,quizID,uid,totalScore,usedTime,seq); xmlWriter.writeXmlFile(); } else{ quizMetaData=new QuizMetaDataXmlReader(answerFilePath+"/"+answerPath); Vector studentAnswer = quizMetaData.getFinalAnswer(); if(studentAnswer!=null && studentAnswer.size()!=0){ for(int i=0;i<studentAnswer.size();i++) { awardedMarks=Integer.parseInt(((QuizFileEntry) studentAnswer.elementAt(i)).getAwardedMarks()); totalScore = totalScore+awardedMarks; } xmlWriter=WriteinScorexml(filePath,quizXmlPath); QuizMetaDataXmlWriter.writeScore(xmlWriter,quizID,uid,totalScore,usedTime,seq); xmlWriter.writeXmlFile(); } else{ xmlWriter=WriteinScorexml(filePath,quizXmlPath); QuizMetaDataXmlWriter.writeScore(xmlWriter,quizID,uid,totalScore,usedTime,seq); xmlWriter.writeXmlFile(); } } //ErrorDumpUtil.ErrorLog("-----QuizMetaDataXmlWriter-----xmlwriteFinalAnswer()-----filename-->"+filename); if(messageFlag.equalsIgnoreCase("submit")) data.setMessage("score is saved successfully" ); }//try catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in quizMetaXmlWriter:xmlwriteFinalScore !!"+e); data.setMessage("some problem to save answer kindly See ExceptionLog !! " ); }//catch }//method end /** * This method write(append/overwrite) final scores in existing xml (score.xml) file * @param xmlWriter XmlWriter * @param quizID String * @param user id String * @param total score String * @param sequence int * @author <a href="mailto:noopur.here@gmail.com">Nupur Dixit</a> */ public static void writeScore(XmlWriter xmlWriter,String quizID,String userID, int totalScore,String usedtime, int seq){ try{ AttributesImpl ats=new AttributesImpl(); String score = String.valueOf(totalScore); ats.addAttribute("","QuizID","","",StringUtil.replaceXmlSpecialCharacters(quizID)); ats.addAttribute("","UserID","","",StringUtil.replaceXmlSpecialCharacters(userID)); ats.addAttribute("","TotalScore","","",StringUtil.replaceXmlSpecialCharacters(score)); ats.addAttribute("","UsedTime","","",StringUtil.replaceXmlSpecialCharacters(usedtime)); if(seq != -1){ xmlWriter.changeAttributes("QuizQuestions",ats,seq); } else{ xmlWriter.appendElement("QuizQuestions",null,ats); } }catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in quizMetaDataXmlWriter method:writeScore !!"+e); } } public static void writeScore(XmlWriter xmlWriter,String quizID,String userID, int totalScore,String usedtime, int seq,String evaluate){ try{ AttributesImpl ats=new AttributesImpl(); String score = String.valueOf(totalScore); ats.addAttribute("","QuizID","","",StringUtil.replaceXmlSpecialCharacters(quizID)); ats.addAttribute("","UserID","","",StringUtil.replaceXmlSpecialCharacters(userID)); ats.addAttribute("","TotalScore","","",StringUtil.replaceXmlSpecialCharacters(score)); ats.addAttribute("","UsedTime","","",StringUtil.replaceXmlSpecialCharacters(usedtime)); ats.addAttribute("","evaluate","","",StringUtil.replaceXmlSpecialCharacters(evaluate)); if(seq != -1){ xmlWriter.changeAttributes("QuizQuestions",ats,seq); } else{ xmlWriter.appendElement("QuizQuestions",null,ats); } }catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in quizMetaDataXmlWriter method:writeScore !!"+e); } } /** This method is responsible for writing student'a answer in userid.xml file * @param filepath String path to userid.xml * @param filename String userid.xml * @param data RunData * @author nupur dixit */ public static void xmlwriteFinalAnswerPractice(String filePath,String quizXmlPath,RunData data){ try{ User user=data.getUser(); String courseid=(String)user.getTemp("course_id"); String courseAlias=CourseUtil.getCourseAlias(courseid); String courseArray[]=courseid.split("_"); int len = courseAlias.length(); int len1 = courseArray[0].length(); String instructorName = (courseid.substring(len, len1)).trim(); String quizID=data.getParameters().getString("quizID",""); String quesID=data.getParameters().getString("quesID",""); String fileName=data.getParameters().getString("fileName",""); String studentAnswer=data.getParameters().getString("finalAnswer",""); String quesType=data.getParameters().getString("quesType",""); String awardedMarks = ""; String markPerQues = data.getParameters().getString("markPerQues",""); XmlWriter xmlWriter=null; File Tempxmls=new File(filePath+"/"+quizXmlPath); QuizMetaDataXmlReader quizMetaData=null; Vector<QuizFileEntry> questionVector = (Vector)user.getTemp("questionvector"); String question,realAnswer,option1,option2,option3,option4; question=realAnswer=option1=option2=option3=option4=""; if(questionVector!=null){ for(int i=0;i<questionVector.size();i++) { String quesid=((QuizFileEntry) questionVector.elementAt(i)).getQuestionID(); String filename=((QuizFileEntry) questionVector.elementAt(i)).getFileName(); if((quesID.equals(quesid)) && (fileName.equals(filename)) ){ question = ((QuizFileEntry) questionVector.elementAt(i)).getQuestion(); realAnswer = ((QuizFileEntry) questionVector.elementAt(i)).getAnswer(); if(quesType.equalsIgnoreCase("mcq")){ option1=((QuizFileEntry) questionVector.elementAt(i)).getOption1(); option2=((QuizFileEntry) questionVector.elementAt(i)).getOption2(); option3=((QuizFileEntry) questionVector.elementAt(i)).getOption3(); option4=((QuizFileEntry) questionVector.elementAt(i)).getOption4(); /*if(studentAnswer.equals("A")) studentAnswer=option1; if(studentAnswer.equals("B")) studentAnswer=option2; if(studentAnswer.equals("C")) studentAnswer=option3; if(studentAnswer.equals("D")) studentAnswer=option4;*/ if(studentAnswer.equals(option1)) studentAnswer="A"; if(studentAnswer.equals(option2)) studentAnswer="B"; if(studentAnswer.equals(option3)) studentAnswer="C"; if(studentAnswer.equals(option4)) studentAnswer="D"; } if(studentAnswer.equalsIgnoreCase(realAnswer)){ awardedMarks = markPerQues; break; } else{ awardedMarks = "0"; break; } } } } boolean foundDuplicate = false; int seq=-1; /** *Checking for xml file presence *@see QuizMetaDataXmlWriter in Util. */ if(!Tempxmls.exists()) { QuizMetaDataXmlWriter.OLESRootOnly(Tempxmls.getAbsolutePath()); } else{ quizMetaData=new QuizMetaDataXmlReader(filePath+"/"+quizXmlPath); Vector finalAnswer=quizMetaData.getFinalAnswer(); if(finalAnswer!=null){ for(int i=0;i<finalAnswer.size();i++) { String quesid=((QuizFileEntry) finalAnswer.elementAt(i)).getQuestionID(); String filename=((QuizFileEntry) finalAnswer.elementAt(i)).getFileName(); if((quesID.equals(quesid)) && (fileName.equals(filename)) ){ foundDuplicate=true; seq = i; break; } } } } if((foundDuplicate==true)&&(seq!=-1)){ xmlWriter=WriteinStudtAnswerxml(filePath,quizXmlPath,quesType,-1); QuizMetaDataXmlWriter.appendAnswerPractice(xmlWriter,quesID,fileName,question,studentAnswer,realAnswer,markPerQues,awardedMarks,option1,option2,option3,option4,0.0,0.0,quesType,seq); xmlWriter.writeXmlFile(); } if((foundDuplicate==false )&&(seq==-1)){ xmlWriter=new XmlWriter(filePath+"/"+quizXmlPath); //-----------------------------------------modify by jaivir and seema-------------------- xmlWriter=WriteinStudtAnswerxml(filePath,quizXmlPath,quesType,seq); //-----------------------------------------modify by jaivir and seema-------------------- QuizMetaDataXmlWriter.appendAnswerPractice(xmlWriter,quesID,fileName,question,studentAnswer,realAnswer,markPerQues,awardedMarks,option1,option2,option3,option4,0.0,0.0,quesType,seq); xmlWriter.writeXmlFile(); } data.setMessage("Answer is saved successfully" ); }//try catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in quizwitere method : xmlwriteFinalAnswerPractice !!"+e); data.setMessage("some problem to save answer kindly See ExceptionLog !! " ); }//catch }//method end public static String calcUsedTime(String maxTime, String remainTime){ String usedTime=""; try{ String usedMin,usedSec; String arr[] = maxTime.split(":"); int totalMax = Integer.valueOf(arr[0])*60 + Integer.valueOf(arr[1]); String arr1[] = remainTime.split(":"); int totalRemain = Integer.valueOf(arr1[0])*60 + Integer.valueOf(arr1[1]); int usedSeconds = totalMax - totalRemain; int usedMinute = usedSeconds/60; int usedSecond = usedSeconds%60; if(usedMinute<10) usedMin = "0" + (String.valueOf(usedMinute)); else usedMin = String.valueOf(usedMinute); if(usedSecond<10) usedSec = "0" + (String.valueOf(usedSecond)); else usedSec = String.valueOf(usedSecond); usedTime = usedMin+":"+usedSec; }catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in quizwitere method : calcUsedTime !!"+e); } return usedTime; } /** This method is responsible for writing marks given by instructor during evaluation in userid.xml file * @param filepath String path to userid.xml * @param filename String userid.xml * @param data RunData * @author nupur dixit */ public static void xmlwriteEvaluateMarks(String answerFilePath,String answerPath,RunData data,String evaluate){ try{ User user=data.getUser(); String courseid=(String)user.getTemp("course_id"); String studentLoginName=data.getParameters().getString("studentLoginName",""); String uid=Integer.toString(UserUtil.getUID(studentLoginName)); String quizID=data.getParameters().getString("quizID",""); String quesID=data.getParameters().getString("quesID",""); String fileName=data.getParameters().getString("fileName",""); String awardedMarks = data.getParameters().getString("awardedMarks",""); boolean flag=false; XmlWriter xmlWriter=null; File answerFile=new File(answerFilePath+"/"+answerPath); QuizMetaDataXmlReader quizMetaData=null; boolean foundDuplicate = false; int seq=-1; String question,studentAnswer,instructorAnswer,markPerQues; question = studentAnswer = instructorAnswer = markPerQues = ""; String questionType=""; /** *Checking for xml file presence *@see QuizMetaDataXmlWriter in Util. */ if(!answerFile.exists()) { QuizMetaDataXmlWriter.OLESRootOnly(answerFile.getAbsolutePath()); } else{ quizMetaData=new QuizMetaDataXmlReader(answerFilePath+"/"+answerPath); Vector finalAnswer=quizMetaData.getFinalAnswer(); if(finalAnswer!=null){ for(int i=0;i<finalAnswer.size();i++) { String quesid=((QuizFileEntry) finalAnswer.elementAt(i)).getQuestionID(); String filename=((QuizFileEntry) finalAnswer.elementAt(i)).getFileName(); question=((QuizFileEntry) finalAnswer.elementAt(i)).getQuestion(); studentAnswer=((QuizFileEntry) finalAnswer.elementAt(i)).getStudentAnswer(); instructorAnswer=((QuizFileEntry) finalAnswer.elementAt(i)).getInstructorAnswer(); markPerQues=((QuizFileEntry) finalAnswer.elementAt(i)).getMarksPerQuestion(); if((quesID.equals(quesid)) && (fileName.equals(filename)) ){ foundDuplicate=true; seq = i; break; } } for(int i=0;i<finalAnswer.size();i++){ questionType=((QuizFileEntry) finalAnswer.elementAt(i)).getQuestionType(); if(questionType.equals("sat") || questionType.equals("lat")){ flag=true; //evaluate ="partial"; break; } } } } if((foundDuplicate==true) &&(seq!=-1)){ xmlWriter=WriteinStudtAnswerxml(answerFilePath,answerPath,questionType,-1); QuizMetaDataXmlWriter.appendAnswerPractice(xmlWriter,quesID,fileName,question,studentAnswer,instructorAnswer,markPerQues,awardedMarks,"","","","",0.0,0.0,questionType,seq); xmlWriter.writeXmlFile(); } quizMetaData=new QuizMetaDataXmlReader(answerFilePath+"/"+answerPath); int getMarks=0; int totalScore=0; Vector studAnswer = quizMetaData.getFinalAnswer(); if(studentAnswer!=null && studAnswer.size()!=0){ for(int i=0;i<studAnswer.size();i++) { getMarks=Integer.parseInt(((QuizFileEntry) studAnswer.elementAt(i)).getAwardedMarks()); totalScore = totalScore+getMarks; } } //String scoreFilePath=TurbineServlet.getRealPath("/Courses"+"/"+courseid+"/Exam/"); String scoreFilePath=TurbineServlet.getRealPath("/Courses"+"/"+courseid+"/Exam/"+quizID); ErrorDumpUtil.ErrorLog("scorefilepath is xmen"+scoreFilePath); String scorePath="score.xml"; String usedTime=""; quizMetaData=new QuizMetaDataXmlReader(scoreFilePath+"/"+scorePath); Vector scoreDetail = quizMetaData.getDetailOfAlreadyInsertedScore(scoreFilePath,scorePath,quizID,uid); XmlWriter xmlScoreWriter = null; if(scoreDetail!=null && scoreDetail.size()!=0){ for(int i=0;i<scoreDetail.size();i++) { usedTime = (((QuizFileEntry) scoreDetail.elementAt(i)).getUsedTime()); seq = Integer.valueOf((((QuizFileEntry) scoreDetail.elementAt(i)).getID())); } } xmlScoreWriter = new XmlWriter(scoreFilePath+"/"+scorePath); if(flag){ xmlScoreWriter=WriteinScorexml(scoreFilePath,scorePath); QuizMetaDataXmlWriter.writeScore(xmlScoreWriter,quizID,uid,totalScore,usedTime,seq,evaluate); // code used in buffer writer then comment above two line /* String tscore=String.valueOf(totalScore); String seq1=String.valueOf(seq); Map m=BufferQuizThread.storage(quizID,uid,tscore,usedTime,seq1,evaluate); ErrorDumpUtil.ErrorLog("Map !!"+m); quizID=(String)m.get("QuizID"); uid=(String)m.get("UserID"); tscore=(String)m.get("TotalScore"); usedTime=(String)m.get("UsedTime"); seq1=(String)m.get("seq"); evaluate=(String)m.get("evaluate"); //xmlScoreWriter=WriteinScorexml(scoreFilePath,scorePath); QuizMetaDataXmlWriter.writeScore(xmlScoreWriter,quizID,uid,Integer.parseInt(tscore),usedTime,Integer.parseInt(seq1),evaluate); //QuizMetaDataXmlWriter.writeScore(xmlScoreWriter,quizID,uid,totalScore,usedTime,seq,evaluate); */ } else{ xmlScoreWriter=WriteinScorexml(scoreFilePath,scorePath); QuizMetaDataXmlWriter.writeScore(xmlScoreWriter,quizID,uid,totalScore,usedTime,seq); } xmlScoreWriter.writeXmlFile(); data.setMessage("score is saved successfully" ); }//try catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in QuizMetaDataXmlWriter !!"+e); data.setMessage("some problem to save answer kindly See ExceptionLog !! " ); }//catch }//method end /** This method is responsible for writing Student ID,Secrity Strings and IP Addrss in xml file. * @author Devendra singhal @author Anand Gupta Add starttime and endtime in xml file. */ //public static void writeSecurityString(XmlWriter xmlWriter,String studentID,String SecurityID,String IPAddress,String Start_time,String End_time){ public static void writeSecurityString(XmlWriter xmlWriter,String studentID,String SecurityID){ try{ //String Start_time=""; //String End_time=""; AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","StudentID","","",studentID); ats.addAttribute("","SecurityID","","",SecurityID); //ats.addAttribute("","IPAddress","","",IPAddress); //ats.addAttribute("","Start_time","","",Start_time); //ats.addAttribute("","End_time","","",End_time); xmlWriter.appendElement("Quiz",null,ats); xmlWriter.writeXmlFile(); }catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in quizMetaDataXmlWriter method:writeScore !!"+e); } } /** This method is responsible for changing IP Address in xml file. * @author Devendra singhal @author Anand Gupta Add startTime and endTime in the xml file. */ public static void updateSecurity(XmlWriter xmlWriter,String studentID,String SecurityID,int seq,String filePath,String xmlfile){ // public static void updateSecurity(XmlWriter xmlWriter,String studentID,String SecurityID,String IPAddress,int seq,String filePath,String xmlfile,String Start_time,String End_time){ try{ AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","StudentID","","",studentID); ats.addAttribute("","SecurityID","","",SecurityID); // ats.addAttribute("","IPAddress","","",IPAddress); // ats.addAttribute("","Start_time","","",Start_time); // ats.addAttribute("","End_time","","",End_time); xmlWriter.changeAttributes("Quiz",ats,seq); xmlWriter.writeXmlFile(); } catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in quizMetaDataXmlWriter method:updateSecurity !!"+e); } } //-------------------------------------------------------IITKanpur--------------------------------- /** *This method read existing xml (Quiz.xml)file and write new xml file with old values * @param filePath String * @param xmlFile String * @return xmlWriter XmlWriter */ public static XmlWriter QuizXml(String filePath,String xmlfile) { XmlWriter xmlWriter=null; File descFile=new File(filePath+"/"+xmlfile); try{ /**Get details from xml file in a vector *after getting details delete the file and create the new file */ QuizMetaDataXmlReader quizMetaData=new QuizMetaDataXmlReader(filePath+"/"+xmlfile); Vector v=quizMetaData.getQuesBanklist_Detail(); descFile.delete(); OLESRootOnly(descFile.getAbsolutePath()); xmlWriter=new XmlWriter(filePath+"/"+xmlfile); if(v!=null) { /**Get the value from vector *and compare the number of attributes for using in other methods */ for(int i=0;i<v.size();i++) { String quizID=((QuizFileEntry)v.get(i)).getQuizID(); String quizName=((QuizFileEntry)v.get(i)).getQuizName(); String maxMarks=((QuizFileEntry)v.get(i)).getMaxMarks(); String maxTime=((QuizFileEntry)v.get(i)).getMaxTime(); String noQuestion=((QuizFileEntry)v.get(i)).getnoQuestion(); String status=((QuizFileEntry)v.get(i)).getQuizStatus(); String Filename=((QuizFileEntry)v.get(i)).getQuizFileName(); String CreationDate=((QuizFileEntry)v.get(i)).getCreationDate(); String ModifiedDate=((QuizFileEntry)v.get(i)).getModifiedDate(); String QuizMode=((QuizFileEntry)v.get(i)).getQuizMode(); String AllowPractice=((QuizFileEntry)v.get(i)).getAllowPractice(); String noofAttr=((QuizFileEntry) v.elementAt(i)).getnoofAttribute(); /**If number of attribute is 16, call method appendQuiz_list *else appendQues_Banklist */ if(noofAttr.equals("16")){ String ExamDate=((QuizFileEntry) v.elementAt(i)).getExamDate(); String StartTime=((QuizFileEntry) v.elementAt(i)).getStartTime(); String ExpiryDate=((QuizFileEntry) v.elementAt(i)).getExpiryDate(); String EndTime=((QuizFileEntry) v.elementAt(i)).getEndTime(); String resDate=((QuizFileEntry) v.elementAt(i)).getResDate(); appendQuiz_list(xmlWriter,quizID,quizName,maxMarks,maxTime,noQuestion,status,Filename,CreationDate,ModifiedDate,QuizMode,ExamDate,StartTime,ExpiryDate,EndTime,AllowPractice,resDate); } else appendQues_Banklist(xmlWriter,quizID,quizName,maxMarks,maxTime,noQuestion,status,Filename,CreationDate,ModifiedDate,QuizMode,AllowPractice); } } } catch(Exception e){ ErrorDumpUtil.ErrorLog("The exception in QuizMetaDataXmlWriter [XmlWriter QuizXml]::"+e); } return xmlWriter; } /** *This method read existing xml file(quizID_Temp_Questions.xml) and write new xml file with old values * @param filePath String * @param xmlFile String * @return xmlWriter XmlWriter */ public static XmlWriter RandomQuizWriteTempxml(String filePath,String xmlfile,String typename) { XmlWriter xmlWriter=null; File descFile=new File(filePath+"/"+xmlfile); //File descFile=new File(filePath+xmlfile); /**Get the details from xml file in a vector *after getting the details delete the xml file and create the new xml file */ // ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---file1--->"+filePath+"/"+xmlfile); // ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---file2--->"+filePath); //ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---file3--->"+xmlfile); try{ QuizMetaDataXmlReader quizMetaData=new QuizMetaDataXmlReader(filePath+"/"+xmlfile); //QuizMetaDataXmlReader quizMetaData=new QuizMetaDataXmlReader(filePath+xmlfile); Vector v=quizMetaData.getRandomTempQuizQuestions(typename); //ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1116---vectorsize--->"+v.size()); descFile.delete(); OLESRootOnly(descFile.getAbsolutePath()); xmlWriter=new XmlWriter(filePath+"/"+xmlfile); String option1="",option2="",option3="",option4="",min="",max="";//,answer=""; /**Read the value from vector and get the tag value */ //ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1130---vectorsize--->"); //ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1131---vectorsize--->"+v.size()); if(v!=null){ //ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1132---vectorsize--->"); for(int i=0;i<v.size();i++) { // ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1136---vectorsize--->"); String quesid=((QuizFileEntry)v.get(i)).getQuestionID(); String question = ((QuizFileEntry)v.get(i)).getQuestion(); String answer = ((QuizFileEntry)v.get(i)).getAnswer(); String quesMarks = ((QuizFileEntry)v.get(i)).getMarksPerQuestion(); String Filename = ((QuizFileEntry)v.get(i)).getFileName(); String Creationdate = ((QuizFileEntry)v.get(i)).getCreationDate(); String noOfAts=((QuizFileEntry)v.get(i)).getnoofAttribute(); /**If number of attribute is 10, call appendRandomQuizSettinglist for MultiChoiceType Question *else appendRandomQuizSettinglist for T/F,ShortAnswer, LongAnswer Type */ //ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1137---vectorsize--->"+question); if(noOfAts.equals("10")) { // ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1152--->"); option1=((QuizFileEntry)v.get(i)).getOption1(); option2=((QuizFileEntry)v.get(i)).getOption2(); option3=((QuizFileEntry)v.get(i)).getOption3(); option4=((QuizFileEntry)v.get(i)).getOption4(); answer = ((QuizFileEntry)v.get(i)).getAnswer(); appendRandomQuizSettinglist(xmlWriter,quesid,question,option1,option2,option3,option4,answer,quesMarks,Filename,Creationdate); } else if(noOfAts.equals("7")) { // ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1163--->"); min=((QuizFileEntry)v.get(i)).getMin(); max=((QuizFileEntry)v.get(i)).getMax(); // ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1167--->"); appendRandomQuizSettinglist(xmlWriter,quesid,question,min,max,quesMarks,Filename,Creationdate); // ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1169--->"); } else { // ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1174--->"); // answer = ((QuizFileEntry)v.get(i)).getAnswer(); // ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1175--->"+question); appendRandomQuizSettinglist(xmlWriter,quesid,question,answer,quesMarks,Filename,Creationdate); } } } // ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----RandomQuizWriteTempxml()---1170---vectorsize--->"); } catch(Exception e){ ErrorDumpUtil.ErrorLog("The exception in QuizMetaDataXmlWriter [XmlWriter RandomQuizWriteTempxml]::"+e); } return xmlWriter; } /** *This method read existing xml file(quizID_QuestionSetting.xml) and write new xml file with old values * @param filePath String * @param xmlFile String * @return xmlWriter XmlWriter */ public static XmlWriter RandomWriteinQues_settingxml(String filePath,String xmlfile) { XmlWriter xmlWriter=null; File descFile=new File(filePath+"/"+xmlfile); try{ /**Get the details from xml file and store in a vector *after storing in xml file delete the xml file and create the new xml file */ QuizMetaDataXmlReader quizMetaData=new QuizMetaDataXmlReader(filePath+"/"+xmlfile); Vector v=quizMetaData.getQuizQuestionDetail(); descFile.delete(); OLESRootOnly(descFile.getAbsolutePath()); xmlWriter=new XmlWriter(filePath+"/"+xmlfile); if(v!=null){ /**Get the value from vector for using in method appendRandomQuizlist*/ for(int i=0;i<v.size();i++) { String topicname=((QuizFileEntry)v.get(i)).getTopic(); String questype = ((QuizFileEntry)v.get(i)).getQuestionType(); String queslevel = ((QuizFileEntry)v.get(i)).getQuestionLevel(); String quesMarks = ((QuizFileEntry)v.get(i)).getMarksPerQuestion(); String noQues = ((QuizFileEntry)v.get(i)).getQuestionNumber(); String ID = ((QuizFileEntry)v.get(i)).getID(); appendRandomQuizlist(xmlWriter,topicname,questype,queslevel,quesMarks,noQues,ID); } } } catch(Exception e){ ErrorDumpUtil.ErrorLog("The exception in QuizMetaDataXmlWriter [XmlWriter RandomWriteinQues_settingxml]::"+e); } return xmlWriter; } /** *This method read existing xml file(quizID_Security.xml) and write new xml file with old values * @param filePath String * @param xmlFile String * @return xmlWriter XmlWriter */ public static XmlWriter WriteinSecurityxml(String filePath,String xmlfile) { XmlWriter xmlWriter=null; File descFile=new File(filePath+"/"+xmlfile); try{ /**Get the details from xml file and store in a vector *after storing in xml file delete the xml file and create the new xml file */ QuizMetaDataXmlReader quizMetaData=new QuizMetaDataXmlReader(filePath+"/"+xmlfile); Vector v=quizMetaData.getSecurityDetail(); descFile.delete(); OLESRootOnly(descFile.getAbsolutePath()); xmlWriter=new XmlWriter(filePath+"/"+xmlfile); if(v!=null){ /**Get the value from vector for using in method writeSecurityString*/ for(int i=0;i<v.size();i++) { String studtid=((QuizFileEntry)v.get(i)).getStudentID(); String securityid = ((QuizFileEntry)v.get(i)).getSecurityID(); //String ipadd = ((QuizFileEntry)v.get(i)).getIP(); //String a= ((QuizFileEntry)v.get(i)).getStartTime(); //String b= ((QuizFileEntry)v.get(i)).getEndTime(); // writeSecurityString(xmlWriter,studtid,securityid,ipadd,a,b); writeSecurityString(xmlWriter,studtid,securityid); } } } catch(Exception e){ ErrorDumpUtil.ErrorLog("The exception in QuizMetaDataXmlWriter [XmlWriter WriteinSecurityxml]::"+e); } return xmlWriter; } /** *This method read existing xml file(uid.xml) and write new xml file with old values * @param filePath String * @param xmlFile String * @return xmlWriter XmlWriter */ public static XmlWriter WriteinStudtAnswerxml(String filePath,String xmlfile,String questype,int seq) { XmlWriter xmlWriter=null; File descFile=new File(filePath+"/"+xmlfile); try { /** Get the details from xml file and store in a vector * after storing in xml file delete the xml file and create the new xml file */ //ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----1399------>"); QuizMetaDataXmlReader quizMetaData=new QuizMetaDataXmlReader(filePath+"/"+xmlfile); Vector v=quizMetaData.getFinalAnswer(); descFile.delete(); OLESRootOnly(descFile.getAbsolutePath()); xmlWriter=new XmlWriter(filePath+"/"+xmlfile); String option1="",option2="",option3="",option4="",min="",max=""; // ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----filePath------>"+filePath); // ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----xmlfile------->"+xmlfile); // ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----vsize------->"+v.size()); if(v!=null) { for(int i=0;i<v.size();i++) { /**Get the values from vector for using in other methods */ String quesid=((QuizFileEntry)v.get(i)).getQuestionID(); String filename = ((QuizFileEntry)v.get(i)).getFileName(); String ques =((QuizFileEntry)v.get(i)).getQuestion(); String stdtans=((QuizFileEntry)v.get(i)).getStudentAnswer(); String Instans=((QuizFileEntry)v.get(i)).getInstructorAnswer(); String quesmark=((QuizFileEntry)v.get(i)).getMarksPerQuestion(); String awardedmark=((QuizFileEntry)v.get(i)).getAwardedMarks(); String noOfAts=((QuizFileEntry)v.get(i)).getnoofAttribute(); //ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----qtype-->"+qtype); // ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----stdtans-->"+stdtans); // ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----Instans-->"+Instans); // ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----noOfAts-->"+noOfAts); //if(questype.equals("mcq")){ if(noOfAts.equals("11")) { option1=((QuizFileEntry)v.get(i)).getOption1(); option2=((QuizFileEntry)v.get(i)).getOption2(); option3=((QuizFileEntry)v.get(i)).getOption3(); option4=((QuizFileEntry)v.get(i)).getOption4(); appendAnswerPractice(xmlWriter,quesid,filename,ques,stdtans,Instans,quesmark,awardedmark,option1,option2,option3,option4,seq); } /* else { ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----questype--->"+questype); appendAnswerPractice(xmlWriter,quesid,filename,ques,stdtans,Instans,quesmark,awardedmark,questype,seq); } */ else if(questype.equalsIgnoreCase("sart")) { //ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----SART"); min=((QuizFileEntry)v.get(i)).getMin(); max=((QuizFileEntry)v.get(i)).getMax(); //ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----1449--min-->"); double min_r = Double.parseDouble(min); double max_r = Double.parseDouble(max); //ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----1452--min-->"+min_r+"-max-->"+max_r); appendAnswerPractice(xmlWriter,quesid,filename,ques,stdtans,min_r,max_r,quesmark,awardedmark,questype,seq); } else { // ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----WriteinStudtAnswerxml()----OTHER--->"); appendAnswerPractice(xmlWriter,quesid,filename,ques,stdtans,Instans,quesmark,awardedmark,questype,seq); } } } } catch(Exception e){ ErrorDumpUtil.ErrorLog("The exception in QuizMetaDataXmlWriter [XmlWriter WriteinSecurityxml]::"+e); } return xmlWriter; } /** *This method read existing xml file(score.xml) and write new xml file with old values * @param filePath String * @param xmlFile String * @return xmlWriter XmlWriter */ public static XmlWriter WriteinScorexml(String filePath,String xmlfile) { int seq=-1; XmlWriter xmlWriter=null; File descFile=new File(filePath+"/"+xmlfile); try{ /**Get the details from xml file and store in a vector *after storing in xml file delete the xml file and create the new xml file */ QuizMetaDataXmlReader quizMetaData=new QuizMetaDataXmlReader(filePath+"/"+xmlfile); Vector v=quizMetaData.attemptedQuiz(); descFile.delete(); OLESRootOnly(descFile.getAbsolutePath()); xmlWriter=new XmlWriter(filePath+"/"+xmlfile); if(v!=null){ /**Get the value from vector for comparing in attributes and use in methods.*/ for(int i=0;i<v.size();i++) { String quizid=((QuizFileEntry)v.get(i)).getQuizID(); String userid = ((QuizFileEntry)v.get(i)).getUserID(); String totalscore =((QuizFileEntry)v.get(i)).getScore(); String usedtime=((QuizFileEntry)v.get(i)).getUsedTime(); String noOfAts=((QuizFileEntry)v.get(i)).getnoofAttribute(); if(noOfAts.equals("5")) { String evaluate=((QuizFileEntry)v.get(i)).getEvaluate(); writeScore(xmlWriter,quizid,userid,Integer.parseInt(totalscore),usedtime,seq,evaluate); } else writeScore(xmlWriter,quizid,userid,Integer.parseInt(totalscore),usedtime,seq); } } } catch(Exception e){ ErrorDumpUtil.ErrorLog("The exception in QuizMetaDataXmlWriter [XmlWriter WriteinSecurityxml]::"+e); } return xmlWriter; } /**Method for append attribute in xml for MultipleChoiceType Question * @param questionID String * @param question String * @param option1 String * @param option2 String * @param option3 String * @param option4 String * @param answer String * @param marks String * @param fileName String * @param creationDate String */ public static void appendRandomQuizSettinglist(XmlWriter xmlWriter,String questionID,String question,String option1, String option2, String option3, String option4, String answer,String marks, String fileName, String creationDate) { AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuestionID","","",StringUtil.replaceXmlSpecialCharacters(questionID)); ats.addAttribute("","Question","","",StringUtil.replaceXmlSpecialCharacters(question)); ats.addAttribute("","OptionA","","",StringUtil.replaceXmlSpecialCharacters(option1)); ats.addAttribute("","OptionB","","",StringUtil.replaceXmlSpecialCharacters(option2)); ats.addAttribute("","OptionC","","",StringUtil.replaceXmlSpecialCharacters(option3)); ats.addAttribute("","OptionD","","",StringUtil.replaceXmlSpecialCharacters(option4)); ats.addAttribute("","Answer","","",StringUtil.replaceXmlSpecialCharacters(answer)); ats.addAttribute("","QuestionMarks","","",StringUtil.replaceXmlSpecialCharacters(marks)); ats.addAttribute("","FileName","","",StringUtil.replaceXmlSpecialCharacters(fileName)); ats.addAttribute("","CreationDate","","",StringUtil.replaceXmlSpecialCharacters(creationDate)); xmlWriter.appendElement("QuizQuestions",null,ats); } /**Method for append attribute in xml for T/F,ShortAnswer,LongAnswer type Question * @param questionID String * @param question String * @param answer String * @param marks String * @param fileName String * @param creationDate String */ public static void appendRandomQuizSettinglist(XmlWriter xmlWriter,String questionID,String question, String answer, String marks, String fileName, String creationDate) { // ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----appendRandomQuizSettinglist()---1397--->"+question); AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuestionID","","",StringUtil.replaceXmlSpecialCharacters(questionID)); ats.addAttribute("","Question","","",StringUtil.replaceXmlSpecialCharacters(question)); ats.addAttribute("","Answer","","",StringUtil.replaceXmlSpecialCharacters(answer)); ats.addAttribute("","QuestionMarks","","",StringUtil.replaceXmlSpecialCharacters(marks)); ats.addAttribute("","FileName","","",StringUtil.replaceXmlSpecialCharacters(fileName)); ats.addAttribute("","CreationDate","","",StringUtil.replaceXmlSpecialCharacters(creationDate)); xmlWriter.appendElement("QuizQuestions",null,ats); } /**Method for append attribute in xml for ShortAnswerRange type Question * @param questionID String * @param question String * @param min String * @param max String * @param marks String * @param fileName String * @param creationDate String */ public static void appendRandomQuizSettinglist(XmlWriter xmlWriter,String questionID,String question,String min,String max, String marks, String fileName, String creationDate) { // ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----appendRandomQuizSettinglist()---1418--->"+question); AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuestionID","","",StringUtil.replaceXmlSpecialCharacters(questionID)); ats.addAttribute("","Question","","",StringUtil.replaceXmlSpecialCharacters(question)); ats.addAttribute("","Min","","",StringUtil.replaceXmlSpecialCharacters(min)); ats.addAttribute("","Max","","",StringUtil.replaceXmlSpecialCharacters(max)); ats.addAttribute("","QuestionMarks","","",StringUtil.replaceXmlSpecialCharacters(marks)); ats.addAttribute("","FileName","","",StringUtil.replaceXmlSpecialCharacters(fileName)); ats.addAttribute("","CreationDate","","",StringUtil.replaceXmlSpecialCharacters(creationDate)); xmlWriter.appendElement("QuizQuestions",null,ats); //ErrorDumpUtil.ErrorLog("QuizMetaDataXmlWriter-----appendRandomQuizSettinglist()---1418--->"); } /** * This method append final answers in existing xml (userid.xml) file for sart type * @param xmlWriter XmlWriter * @param questionID String * @param file name String * @param min String * @param max String * @param marks per question String * @param awarded marks String * @param sequence int * @author <a href="mailto:noopur.here@gmail.com">Nupur Dixit</a> */ public static void appendAnswerPractice(XmlWriter xmlWriter,String questionID,String fileName,String question,String studentAnswer,double min,double max,String markPerQues,String awardedMarks,String quesType, int seq){ try{ String min_r = String.valueOf(min);//min.toString(); String max_r = String.valueOf(max);//max.toString(); ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----appendAnswerPractice()---min&max"); AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuestionID","","",StringUtil.replaceXmlSpecialCharacters(questionID)); ats.addAttribute("","FileName","","",StringUtil.replaceXmlSpecialCharacters(fileName)); ats.addAttribute("","Question","","",StringUtil.replaceXmlSpecialCharacters(question)); ats.addAttribute("","StudentAnswer","","",StringUtil.replaceXmlSpecialCharacters(studentAnswer)); //ats.addAttribute("","InstructorAnswer","","",StringUtil.replaceXmlSpecialCharacters(realAnswer)); ats.addAttribute("","Min","","",StringUtil.replaceXmlSpecialCharacters(min_r)); ats.addAttribute("","Max","","",StringUtil.replaceXmlSpecialCharacters(max_r)); ats.addAttribute("","QuestionMarks","","",StringUtil.replaceXmlSpecialCharacters(markPerQues)); ats.addAttribute("","AwardedMarks","","",StringUtil.replaceXmlSpecialCharacters(awardedMarks)); if(seq != -1){ xmlWriter.changeAttributes("QuizQuestions",ats,seq); } else{ xmlWriter.appendElement("QuizQuestions",null,ats); } }catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in quiz writer method :appendAnswerPractice !!"+e); // data.setMessage("some problem to save answer kindly See ExceptionLog !! " ); } } /** * This method append final answers in existing xml (userid.xml) file * @param xmlWriter XmlWriter * @param questionID String * @param file name String * @param Answer String * @param marks per question String * @param awarded marks String * @param sequence int * @author <a href="mailto:noopur.here@gmail.com">Nupur Dixit</a> */ public static void appendAnswerPractice(XmlWriter xmlWriter,String questionID,String fileName,String question,String studentAnswer,String realAnswer,String markPerQues,String awardedMarks,String quesType, int seq){ try{ //ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----appendAnswerPractice()---other"); AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuestionID","","",StringUtil.replaceXmlSpecialCharacters(questionID)); ats.addAttribute("","FileName","","",StringUtil.replaceXmlSpecialCharacters(fileName)); ats.addAttribute("","Question","","",StringUtil.replaceXmlSpecialCharacters(question)); ats.addAttribute("","StudentAnswer","","",StringUtil.replaceXmlSpecialCharacters(studentAnswer)); ats.addAttribute("","InstructorAnswer","","",StringUtil.replaceXmlSpecialCharacters(realAnswer)); ats.addAttribute("","QuestionMarks","","",StringUtil.replaceXmlSpecialCharacters(markPerQues)); ats.addAttribute("","AwardedMarks","","",StringUtil.replaceXmlSpecialCharacters(awardedMarks)); if(seq != -1){ xmlWriter.changeAttributes("QuizQuestions",ats,seq); } else{ xmlWriter.appendElement("QuizQuestions",null,ats); } }catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in quiz writer method :appendAnswerPractice !!"+e); // data.setMessage("some problem to save answer kindly See ExceptionLog !! " ); } } /**Method for append answer practice attribute in xml * @param questionID String * @param fileName String * @param question String * @param studentAnswer String * @param realAnswer String * @param markPerQues String * @param awardedMarks String * @param option1 String * @param option2 String * @param option3 String * @param option4 String * @param seq int */ public static void appendAnswerPractice(XmlWriter xmlWriter,String questionID,String fileName,String question,String studentAnswer,String realAnswer,String markPerQues,String awardedMarks,String option1,String option2,String option3,String option4, int seq){ try{ //ErrorDumpUtil.ErrorLog("----QuizMetaDataXmlWriter----appendAnswerPractice()--option--"); AttributesImpl ats=new AttributesImpl(); ats.addAttribute("","QuestionID","","",StringUtil.replaceXmlSpecialCharacters(questionID)); ats.addAttribute("","FileName","","",StringUtil.replaceXmlSpecialCharacters(fileName)); ats.addAttribute("","Question","","",StringUtil.replaceXmlSpecialCharacters(question)); ats.addAttribute("","StudentAnswer","","",StringUtil.replaceXmlSpecialCharacters(studentAnswer)); ats.addAttribute("","InstructorAnswer","","",StringUtil.replaceXmlSpecialCharacters(realAnswer)); ats.addAttribute("","QuestionMarks","","",StringUtil.replaceXmlSpecialCharacters(markPerQues)); ats.addAttribute("","AwardedMarks","","",StringUtil.replaceXmlSpecialCharacters(awardedMarks)); ats.addAttribute("","OptionA","","",StringUtil.replaceXmlSpecialCharacters(option1)); ats.addAttribute("","OptionB","","",StringUtil.replaceXmlSpecialCharacters(option2)); ats.addAttribute("","OptionC","","",StringUtil.replaceXmlSpecialCharacters(option3)); ats.addAttribute("","OptionD","","",StringUtil.replaceXmlSpecialCharacters(option4)); /**If Sequence is -1, call changeAttributes of xmlWriter *else call appendElement of xmlWriter */ if(seq != -1){ xmlWriter.changeAttributes("QuizQuestions",ats,seq); } else{ xmlWriter.appendElement("QuizQuestions",null,ats); } }catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in quiz writer method :appendAnswerPractice !!"+e); // data.setMessage("some problem to save answer kindly See ExceptionLog !! " ); } } /** * This method append element in existing xml (quizid_PracticeQuizInfo.xml) file * @param xmlWriter XmlWriter * @param topic name String * @param type of question String * @author <a href="mailto:palseema@rediffmail.com">Manorama Pal</a> */ public static void appendPracticeQuizInfo(XmlWriter xmlWriter,String StudentID,int NoofAttempt,int seq) { try{ AttributesImpl ats=new AttributesImpl(); String Attemptno = String.valueOf(NoofAttempt); ats.addAttribute("","StudentID","","",StringUtil.replaceXmlSpecialCharacters(StudentID)); ats.addAttribute("","NoofAttempt","","",StringUtil.replaceXmlSpecialCharacters(Attemptno)); if(seq != -1){ xmlWriter.changeAttributes("Quiz",ats,seq); } else{ xmlWriter.appendElement("Quiz",null,ats); } } catch(Exception e){ ErrorDumpUtil.ErrorLog("Error in QuizMetaDataXmlWriter method :appendPracticeQuizInfo !!"+e); } } /** *This method read existing xml file(quizID_PracticeQuizInfo.xml) and write new xml file with old values * @param filePath String * @param xmlFile String * @return xmlWriter XmlWriter */ public static XmlWriter Write_PracticeQuizInfoxml(String filePath,String xmlfile) { int seq=-1; XmlWriter xmlWriter=null; File descFile=new File(filePath+"/"+xmlfile); try{ /**Get the details from xml file and store in a vector *after storing in xml file delete the xml file and create the new xml file */ QuizMetaDataXmlReader quizMetaData=new QuizMetaDataXmlReader(filePath+"/"+xmlfile); Vector v=quizMetaData.getAttemptPracticeQuizDetail(); descFile.delete(); OLESRootOnly(descFile.getAbsolutePath()); xmlWriter=new XmlWriter(filePath+"/"+xmlfile); if(v!=null){ /**Get the value from vector for comparing in attributes and use in methods.*/ for(int i=0;i<v.size();i++) { String studentid = ((QuizFileEntry)v.get(i)).getStudentID(); String noofattempt =((QuizFileEntry)v.get(i)).getNoofAttempt(); appendPracticeQuizInfo(xmlWriter,studentid,Integer.parseInt(noofattempt),seq); } } } catch(Exception e){ ErrorDumpUtil.ErrorLog("The exception in QuizMetaDataXmlWriter [XmlWriter Write_PracticeQuizInfoxml]:"+e); } return xmlWriter; } //-------------------------------------------------------IITKanpur--------------------------------- }
50.985042
332
0.64802
5d7afef871a5173bac7d6ec2bb6d76abbd7b2195
457
package com.simplicity.maged.mccobjectdetection.components.contextManager; import java.util.UUID; public class EnvironmentContext { public UUID providerUUID; public double upBW3; // Cloud<-->Mobile_System public double downBW3; public double upBW4; // Cloud<-->Data_Provider public double downBW4; public double upBW5; // Cloud<-->User_App public double downBW5; public long computeSpeed; public double memoryAvail; public double energyAvail; }
26.882353
74
0.789934
194a1175ac540a1306563dfc956ef098a6e65e0c
36,289
package com.gymnast.view.hotinfoactivity.activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.gymnast.App; import com.gymnast.R; import com.gymnast.data.hotinfo.RecentActivityDetail; import com.gymnast.data.hotinfo.UserDevas; import com.gymnast.data.net.API; import com.gymnast.utils.CallBackUtil; import com.gymnast.utils.CollectUtil; import com.gymnast.utils.DataCleanManagerUtil; import com.gymnast.utils.PicUtil; import com.gymnast.utils.PicassoUtil; import com.gymnast.utils.PostUtil; import com.gymnast.utils.RefreshUtil; import com.gymnast.utils.StringUtil; import com.gymnast.utils.TimeUtil; import com.gymnast.view.ImmersiveActivity; import com.gymnast.view.home.adapter.HotInfoActivityUserRecyclerViewAdapter; import com.gymnast.view.hotinfoactivity.adapter.CallBackAdapter; import com.gymnast.view.hotinfoactivity.entity.CallBackDetailEntity; import com.gymnast.view.hotinfoactivity.entity.CallBackEntity; import com.gymnast.view.personal.listener.WrapContentLinearLayoutManager; import com.gymnast.view.user.LoginActivity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; /** * Created by Cymbi on 2016/8/22. */ public class ActivityDetailsActivity extends ImmersiveActivity implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener{ private TextView tvDetailTitle,tvDetailMoney,tvDetailPeopleNumber,tvDetailSignUp,tvDetailAddress,tvDetailTime,tvDetailPhone,tvDetailCountDown,tvCollect,tvReport,tvDelete, tvSpacial,tvTop; private ImageView ivDetailImage,ivClose,ivBack,ivMoreChoice; private View view; SwipeRefreshLayout reflesh; private RecyclerView rvCallBack; private RecyclerView rvActiveUserList; private EditText etCallBack; private TextView tvCallBackSend; RelativeLayout rlAll; LinearLayout llShareToFriends,llShareToWeiChat,llShareToQQ,llShareToQQZone,llShareToMicroBlog; private WebView tvDescContent; public static int shareNumber=0;//分享次数 private long startTime,endTime,lastTime; private String phone,descContent,title,imageUrl,address,token,userId,nickName,phoneNew,maxPeople="0"; private int price,surplusPeople,x,memberCount; private int Userid; private int UserId; int activeID; int notifyPos=0; String avatar; private SharedPreferences share; RecentActivityDetail recentActiveData; List<CallBackEntity> commentList=new ArrayList<>(); List<UserDevas> userWantToGo=new ArrayList<>(); CallBackAdapter commentAdapter; boolean isCollected; HotInfoActivityUserRecyclerViewAdapter userLikeAdapter; public static boolean isComment=true; public static final int HANDLE_BANNER_ACTIVE_DATA=1; public static final int HANDLE_NEW_ACTIVE_DATA=2; public static final int HANDLE_SEARCH_ACTIVE_DATA=3; public static final int HANDLE_HISTORY_DATA=4; public static final int HANDLE_COMMENT_DATA=5; public static final int HANDLE_MAIN_USER_BACK=6; public static final int HANDLE_USER_WANT_TO_GO=7; static ArrayList<CallBackDetailEntity> detailMSGs; ArrayList<String> userABC=new ArrayList<>(); Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case CollectUtil.TO_COLLECT: Toast.makeText(ActivityDetailsActivity.this,"已收藏!",Toast.LENGTH_SHORT).show(); tvCollect.setText("取消收藏"); isCollected=true; break; case CollectUtil.CANCEL_COLLECT: Toast.makeText(ActivityDetailsActivity.this,"已取消收藏!",Toast.LENGTH_SHORT).show(); tvCollect.setText("收藏"); isCollected=false; break; case CollectUtil.ERROR: Toast.makeText(ActivityDetailsActivity.this,"服务器异常!",Toast.LENGTH_SHORT).show(); break; case HANDLE_USER_WANT_TO_GO: userLikeAdapter=new HotInfoActivityUserRecyclerViewAdapter(ActivityDetailsActivity.this,userWantToGo); WrapContentLinearLayoutManager manager1=new WrapContentLinearLayoutManager(ActivityDetailsActivity.this,LinearLayoutManager.HORIZONTAL,false); rvActiveUserList.setLayoutManager(manager1); rvActiveUserList.setAdapter(userLikeAdapter); break; case HANDLE_MAIN_USER_BACK: commentAdapter.notifyItemChanged(notifyPos); break; case HANDLE_COMMENT_DATA: userABC= (ArrayList<String>) msg.obj; commentAdapter=new CallBackAdapter(ActivityDetailsActivity.this,commentList); WrapContentLinearLayoutManager manager=new WrapContentLinearLayoutManager(ActivityDetailsActivity.this,LinearLayoutManager.VERTICAL,false); rvCallBack.setLayoutManager(manager); rvCallBack.setAdapter(commentAdapter); commentAdapter.setOnItemClickListener(new CallBackAdapter.OnItemClickListener() { @Override public void OnCallBackClick(View view,int position, ArrayList<CallBackDetailEntity> detailMSGs) { isComment=false; notifyPos=position; ActivityDetailsActivity.detailMSGs=detailMSGs; ActivityDetailsActivity.type=ActivityDetailsActivity.CALL_BACK_TYPE_ONE; String backWho=commentList.get(position).getCallBackNickName(); firstCommenter=backWho; etCallBack.requestFocus(); etCallBack.setText(""); etCallBack.setHint("回复" + backWho); InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (inputManager.isActive()) { inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS); ActivityDetailsActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); } } }); break; case HANDLE_BANNER_ACTIVE_DATA: handleData(); break; case HANDLE_NEW_ACTIVE_DATA: handleData(); break; case HANDLE_SEARCH_ACTIVE_DATA: handleData(); break; case HANDLE_HISTORY_DATA: handleHistoryData(); break; } } }; private void autoRefresh(){ InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(etCallBack.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); RefreshUtil.refresh(reflesh, this); setBaseState(); setCallBackView(); commentAdapter.notifyDataSetChanged(); rvCallBack.scrollToPosition(3); etCallBack.setFocusable(true); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 reflesh.setRefreshing(false); } }, 1000); } private void handleHistoryData() { ivMoreChoice.setVisibility(View.GONE); tvDetailTime.setText(TimeUtil.getDetailTime(startTime) + "~" + TimeUtil.getDetailTime(endTime)); tvDetailTitle.setText(title + ""); PicassoUtil.handlePic(ActivityDetailsActivity.this, PicUtil.getImageUrlDetail(ActivityDetailsActivity.this, StringUtil.isNullAvatar(imageUrl), x, 1920), ivDetailImage, x, 720); if(price==0){ tvDetailMoney.setText("免费"); }else { tvDetailMoney.setText("¥"+price); } tvDetailAddress.setText(address+""); tvDetailPhone.setText(phone + ""); tvDetailPeopleNumber.setVisibility(View.INVISIBLE); tvDetailCountDown.setText("活动已结束"); WindowManager wm = (WindowManager) ActivityDetailsActivity.this.getSystemService(Context.WINDOW_SERVICE); int width = wm.getDefaultDisplay().getWidth(); if(width > 520){ this.tvDescContent.setInitialScale(160); }else if(width > 450){ this.tvDescContent.setInitialScale(140); }else if(width > 300){ this.tvDescContent.setInitialScale(120); }else{ this.tvDescContent.setInitialScale(100); } tvDescContent.loadDataWithBaseURL(null, descContent, "text/html", "utf-8", null); tvDescContent.getSettings().setJavaScriptEnabled(true); // 设置启动缓存 ; tvDescContent.getSettings().setAppCacheEnabled(true); tvDescContent.setWebChromeClient(new WebChromeClient()); tvDescContent.getSettings().setJavaScriptEnabled(true); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); setContentView(R.layout.activity_activity_details); Rect rect = new Rect(); ActivityDetailsActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); x = rect.width(); getInfo(); setView(); setCallBackView(); initData(); try{ Userid=Integer.parseInt(userId);}catch (Exception e){e.printStackTrace();} getSignUpInfo(); getCollectionMenber(); getPageView(); } private void getPageView() { new Thread(new Runnable() { @Override public void run() { String uri=API.BASE_URL+"/v1/pageViwes"; HashMap<String,String>params=new HashMap<>(); params.put("types",2+""); params.put("typeId",activeID+""); String result= PostUtil.sendPostMessage(uri,params); } }).start(); } private void getCollectionMenber() { new Thread(){ @Override public void run() { try{ String uri=API.BASE_URL+"/v1/collect/users "; HashMap<String,String> params=new HashMap<String, String>(); params.put("model","1"); params.put("modelId",activeID+""); String result=PostUtil.sendPostMessage(uri,params); JSONObject object=new JSONObject(result); if (object.getInt("state")!=200){ userWantToGo=new ArrayList<UserDevas>(); return; } JSONArray array=object.getJSONArray("data"); for (int i=0;i<array.length();i++){ JSONObject data=array.getJSONObject(i); UserDevas userDevas=new UserDevas(); userDevas.id=data.getInt("id"); userDevas.nickname=data.getString("nickname"); userDevas.imageUrl=data.getString("avatar"); userDevas.bgmUrl=data.getString("avatar"); userWantToGo.add(userDevas); } handler.sendEmptyMessage(HANDLE_USER_WANT_TO_GO); }catch (Exception e){ e.printStackTrace(); } } }.start(); } String firstCommenter=""; private void setCallBackView() { CallBackUtil.getCallBackData(2, activeID, commentList, handler, HANDLE_COMMENT_DATA); reflesh.setRefreshing(false); } private void getSignUpInfo() { new Thread(new Runnable() { @Override public void run() { String uri=API.BASE_URL+"/v1/activity/memberPeople"; HashMap<String,String> params=new HashMap<String, String>(); params.put("token",token); params.put("activityId",activeID+""); params.put("userId",userId); String result=PostUtil.sendPostMessage(uri,params); try { JSONObject object=new JSONObject(result); if(object.getInt("state")==200){ runOnUiThread(new Runnable() { @Override public void run() { tvDetailSignUp.setText("已报名"); tvDetailSignUp.setBackgroundColor(getResources().getColor(R.color.background)); tvDetailSignUp.setClickable(false); } }); }else if(object.getInt("state")==10002){ runOnUiThread(new Runnable() { @Override public void run() { tvDetailSignUp.setText("报名"); } }); } } catch (JSONException e) { e.printStackTrace(); } } }).start(); } private void getInfo() { share= getSharedPreferences("UserInfo", Context.MODE_PRIVATE); token = share.getString("Token", ""); userId = share.getString("UserId","");//当前用户id nickName = share.getString("NickName", ""); avatar = share.getString("Avatar", ""); phoneNew = share.getString("Phone",""); Intent data=getIntent(); activeID=data.getIntExtra("ActiveID", 0); UserId=data.getIntExtra("UserId", 0); recentActiveData= (RecentActivityDetail) data.getSerializableExtra("RecentActivityDetail"); } private void setView() { reflesh = (SwipeRefreshLayout) findViewById(R.id.srlReflesh); RefreshUtil.refresh(reflesh,this); etCallBack= (EditText) findViewById(R.id.etCallBack); etCallBack.setHint("说点什么吧。。。"); etCallBack.setText(""); etCallBack.setTextColor(Color.parseColor("#999999")); tvCallBackSend= (TextView) findViewById(R.id.tvCallBackSend); rvCallBack= (RecyclerView) findViewById(R.id.rvCallBack); rvActiveUserList= (RecyclerView) findViewById(R.id.rvActiveUserList); rlAll= (RelativeLayout) findViewById(R.id.rlAll); ivDetailImage=(ImageView) findViewById(R.id.ivDetailImage); ivBack=(ImageView) findViewById(R.id.ivDetailBack); tvDetailTitle=(TextView) findViewById(R.id.tvDetailTitle); tvDetailCountDown=(TextView) findViewById(R.id.tvDetailCountDown); tvDetailMoney=(TextView) findViewById(R.id.tvDetailMoney); tvDetailPeopleNumber=(TextView) findViewById(R.id.tvDetailPeopleNumber); tvDetailSignUp=(TextView) findViewById(R.id.tvDetailSignUp); tvDetailAddress=(TextView) findViewById(R.id.tvDetailAddress); tvDetailTime=(TextView) findViewById(R.id.tvDetailTime); tvDetailPhone=(TextView) findViewById(R.id.tvDetailPhone); tvDescContent=(WebView) findViewById(R.id.tvDescContent); ivMoreChoice= (ImageView) findViewById(R.id.ivMoreChoice); view = getLayoutInflater().inflate(R.layout.share_dialog, null); llShareToFriends= (LinearLayout) view.findViewById(R.id.llShareToFriends); llShareToWeiChat= (LinearLayout) view.findViewById(R.id.llShareToWeiChat); llShareToQQ= (LinearLayout) view.findViewById(R.id.llShareToQQ); llShareToQQZone= (LinearLayout) view.findViewById(R.id.llShareToQQZone); llShareToMicroBlog= (LinearLayout) view.findViewById(R.id.llShareToMicroBlog); tvCollect= (TextView) view.findViewById(R.id.tvCollect); tvReport= (TextView) view.findViewById(R.id.tvReport); tvDelete= (TextView) view.findViewById(R.id.tvDelete); tvTop= (TextView) view.findViewById(R.id.tvTop); tvSpacial= (TextView) view.findViewById(R.id.tvSpacial); ivClose= (ImageView) view.findViewById(R.id.ivClose); tvTop.setVisibility(View.GONE); tvSpacial.setVisibility(View.GONE); tvDelete.setVisibility(View.GONE); ivMoreChoice.setOnClickListener(this); llShareToFriends.setOnClickListener(this); llShareToWeiChat.setOnClickListener(this); llShareToQQ.setOnClickListener(this); llShareToQQZone.setOnClickListener(this); llShareToMicroBlog.setOnClickListener(this); tvCollect.setOnClickListener(this); tvReport.setOnClickListener(this); tvDelete.setOnClickListener(this); tvTop.setOnClickListener(this); tvSpacial.setOnClickListener(this); tvDetailSignUp.setOnClickListener(this); tvDetailPeopleNumber.setOnClickListener(this); tvCallBackSend.setOnClickListener(this); reflesh.setOnRefreshListener(this); tvDetailPhone.setOnClickListener(this); final Dialog dialog= new Dialog(this,R.style.Dialog_Fullscreen); getWindow().setBackgroundDrawableResource(android.R.color.transparent); dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)); Window window = dialog.getWindow(); // 设置显示动画 window.setWindowAnimations(R.style.main_menu_animstyle); WindowManager.LayoutParams wl = window.getAttributes(); wl.x = 0; wl.y = getWindowManager().getDefaultDisplay().getHeight(); // 以下这两句是为了保证按钮可以水平满屏 wl.width = ViewGroup.LayoutParams.MATCH_PARENT; wl.height = ViewGroup.LayoutParams.WRAP_CONTENT; // 设置显示位置 dialog.onWindowAttributesChanged(wl); // 设置点击外围解散 dialog.setCanceledOnTouchOutside(true); ivMoreChoice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { view.setVisibility(View.VISIBLE); dialog.show(); } }); ivClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); ivBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } private void initData() { if (recentActiveData==null&&activeID!=0){ getMSGFromNetwork(activeID); }else { memberCount=recentActiveData.getLoverNum(); maxPeople=recentActiveData.getMaxpeople(); startTime=recentActiveData.getStartTime(); endTime=recentActiveData.getEndTime(); phone=recentActiveData.getPhone(); descContent=recentActiveData.getDetail(); title=recentActiveData.getTitle(); activeID=recentActiveData.getId(); price=recentActiveData.getPrice(); imageUrl=recentActiveData.getPictureURL(); address=recentActiveData.getAddress(); handler.sendEmptyMessage(HANDLE_HISTORY_DATA); } reflesh.setRefreshing(false); } public void getMSGFromNetwork(final int ID){ new Thread(){ @Override public void run() { try { String url= API.BASE_URL+"/v1/activity/query"; HashMap<String,String> params=new HashMap<>(); params.put("id",ID+""); params.put("pageNumber",1+""); params.put("createId",userId); params.put("page", 1 + ""); String result= PostUtil.sendPostMessage(url,params); JSONObject object=new JSONObject(result); JSONArray array=object.getJSONArray("data"); JSONObject data=array.getJSONObject(0); memberCount=data.getInt("memberCount"); isCollected=((data.getInt("isCollection"))==1)?true:false; activeID=data.getInt("id"); maxPeople=data.getString("maxPeople"); startTime=data.getLong("startTime"); endTime=data.getLong("endTime"); lastTime=data.getLong("lastTime"); phone=data.getString("phone"); descContent=data.getString("descContent"); title=data.getString("title"); price=data.getInt("price"); imageUrl=data.getString("imgUrls"); address=data.getString("address"); handler.sendEmptyMessage(HANDLE_NEW_ACTIVE_DATA); }catch (Exception e){ e.printStackTrace(); } } }.start(); } private void handleData(){ Long systemTime = new Date(System.currentTimeMillis()).getTime();//获取当前时间 surplusPeople = Integer.valueOf(maxPeople)-memberCount; //剩余报名人数 tvDetailTime.setText(TimeUtil.getDetailTime(startTime)+"~"+TimeUtil.getDetailTime(endTime)); tvDetailTitle.setText(title+""); PicassoUtil.handlePic(ActivityDetailsActivity.this, PicUtil.getImageUrlDetail(ActivityDetailsActivity.this, StringUtil.isNullAvatar(imageUrl), x, 1920),ivDetailImage,x,720); if(price==0){ tvDetailMoney.setText("免费"); }else { tvDetailMoney.setText("¥"+price); } tvDetailAddress.setText(address+""); tvDetailPhone.setText(phone+""); if(maxPeople==null){ tvDetailPeopleNumber.setText("已报名"+memberCount); }else { if(surplusPeople>100000){ tvDetailPeopleNumber.setText("已报名"+memberCount+", "+"无限制"); }else { tvDetailPeopleNumber.setText("已报名" + memberCount + ", " + "剩余" + surplusPeople + "个名额"); } } if(systemTime>=startTime&&systemTime<=endTime){ tvDetailCountDown.setText("活动已开始"); } if(systemTime>=startTime&&systemTime>=endTime){ tvDetailCountDown.setText("活动已结束"); tvDetailSignUp.setBackgroundColor(getResources().getColor(R.color.background)); tvDetailSignUp.setClickable(false); } if(systemTime<startTime){ String disTime=TimeUtil.getDisTime(systemTime, startTime); tvDetailCountDown.setText("活动倒计时:"+disTime); tvDetailSignUp.setText("报名"); } WindowManager wm = (WindowManager) ActivityDetailsActivity.this.getSystemService(Context.WINDOW_SERVICE); int width = wm.getDefaultDisplay().getWidth(); if(width > 520){ this.tvDescContent.setInitialScale(160); }else if(width > 450){ this.tvDescContent.setInitialScale(140); }else if(width > 300){ this.tvDescContent.setInitialScale(120); }else{ this.tvDescContent.setInitialScale(100); } tvDescContent.loadDataWithBaseURL(null, descContent, "text/html", "utf-8", null); tvDescContent.getSettings().setJavaScriptEnabled(true); // 设置启动缓存 ; tvDescContent.getSettings().setAppCacheEnabled(true); tvDescContent.setWebChromeClient(new WebChromeClient()); tvDescContent.getSettings().setJavaScriptEnabled(true); if (isCollected){ tvCollect.setText("取消收藏"); }else { tvCollect.setText("收藏"); } } private void shareToFriends() { if (!checkLogIn()){return;}; Toast.makeText(this, "分享到朋友圈!", Toast.LENGTH_SHORT).show(); shareNumber++; } private void shareToWeiChat() { if (!checkLogIn()){return;}; Toast.makeText(this,"分享到微信!",Toast.LENGTH_SHORT).show(); shareNumber++; } private void shareToQQ() { if (!checkLogIn()){return;}; Toast.makeText(this,"分享到QQ!",Toast.LENGTH_SHORT).show(); shareNumber++; } private void shareToQQZone() { if (!checkLogIn()){return;}; Toast.makeText(this,"分享到QQ空间!",Toast.LENGTH_SHORT).show(); shareNumber++; } private void shareToMicroBlog() { if (!checkLogIn()){return;}; Toast.makeText(this,"分享到微博!",Toast.LENGTH_SHORT).show(); shareNumber++; } private void collect() { if (!checkLogIn()){return;}; if (isCollected){ CollectUtil.goToCancelCollect(handler, token, 1, activeID); }else { CollectUtil.goToCollect(handler,token,1,activeID); } } private void report() { if (!checkLogIn()){return;}; Toast.makeText(this,"已举报!",Toast.LENGTH_SHORT).show(); } private void delete() { if (!checkLogIn()){return;}; Toast.makeText(this,"已删除!",Toast.LENGTH_SHORT).show(); } private void spacial() { if (!checkLogIn()){return;}; Toast.makeText(this,"已加精!",Toast.LENGTH_SHORT).show(); } private void toTop() { if (!checkLogIn()){return;}; Toast.makeText(this,"已置顶!",Toast.LENGTH_SHORT).show(); } private boolean checkLogIn(){ boolean isStateOk=true; if (!App.isNetStateOK){ Toast.makeText(this,"亲,没网了呢!",Toast.LENGTH_SHORT).show(); isStateOk=false; }else { if (token.equals("") || !App.isStateOK) { Toast.makeText(this, "您还没登陆呢,亲!", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(ActivityDetailsActivity.this, LoginActivity.class); ActivityDetailsActivity.this.startActivity(intent); isStateOk = false; } } return isStateOk; } @Override public void onClick(View view) { switch (view.getId()){ case R.id.tvCallBackSend: handleSendMSG(); break; case R.id.llShareToFriends: shareToFriends(); break; case R.id.llShareToWeiChat: shareToWeiChat(); break; case R.id.llShareToQQ: shareToQQ(); break; case R.id.llShareToQQZone: shareToQQZone(); break; case R.id.llShareToMicroBlog: shareToMicroBlog(); break; case R.id.tvCollect: collect(); break; case R.id.tvReport: report(); break; case R.id.tvDelete: delete(); break; case R.id.tvSpacial: spacial(); break; case R.id.tvTop: toTop(); break; case R.id.tvDetailPhone: final AlertDialog builder = new AlertDialog.Builder(ActivityDetailsActivity.this).create(); builder.setView(getLayoutInflater().inflate(R.layout.activity_personal_dialog, null)); builder.show(); //去掉dialog四边的黑角 builder.getWindow().setBackgroundDrawable(new BitmapDrawable()); TextView text=(TextView) builder.getWindow().findViewById(R.id.text); text.setText("直接拨打"+tvDetailPhone.getText()+"?"); builder.getWindow().findViewById(R.id.dialog_cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { builder.dismiss(); } }); TextView dialog_confirm=(TextView)builder.getWindow().findViewById(R.id.dialog_confirm); dialog_confirm.setText("拨打"); dialog_confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+tvDetailPhone.getText().toString().trim())); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); builder.dismiss(); } }); break; case R.id.tvDetailPeopleNumber: if (!checkLogIn()){return;}; //首页banner还没有传参数过来 if(UserId==Userid){ Intent i=new Intent(ActivityDetailsActivity.this,AuditActivity.class); i.putExtra("activityId",activeID); startActivity(i); }else {} break; case R.id.tvDetailSignUp: if (!checkLogIn()){return;}; Intent i=new Intent(ActivityDetailsActivity.this,SignUpActivity.class); i.putExtra("activityId",activeID); i.putExtra("imageUrl",imageUrl); i.putExtra("title",title); i.putExtra("price",price); startActivityForResult(i,100); break; } } String toNickName; public static final int CALL_BACK_TYPE_ONE=1111; public static final int CALL_BACK_TYPE_TWO=2222; public static int type; private void handleSendMSG() { toNickName=etCallBack.getHint().toString().trim().substring(2); if(!App.isStateOK|token.equals("")){ Toast.makeText(ActivityDetailsActivity.this,"您还没有登录,请登陆!",Toast.LENGTH_SHORT).show(); ActivityDetailsActivity.this.startActivity(new Intent(ActivityDetailsActivity.this,LoginActivity.class)); return; }else { String comment = etCallBack.getText().toString().trim(); if (isComment) { if (comment.equals("")) { Toast.makeText(ActivityDetailsActivity.this, "回复内容为空!", Toast.LENGTH_SHORT).show();//非空判断 setBaseState(); return; } else {//评论活动 etCallBack.setText(""); InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(etCallBack.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); CallBackUtil.handleCallBackMSG(2, activeID, Integer.valueOf(userId), comment); CallBackEntity entity = new CallBackEntity(); entity.setCallBackImgUrl(StringUtil.isNullAvatar(avatar)); entity.setCallBackNickName(nickName); entity.setCallBackTime(System.currentTimeMillis()); entity.setCallBackText(comment); entity.setEntities(new ArrayList<CallBackDetailEntity>()); commentList.add(entity); commentAdapter.notifyItemChanged(commentList.size() - 1); rvCallBack.scrollToPosition(0); autoRefresh(); } } else { if (comment.equals("")) { Toast.makeText(ActivityDetailsActivity.this, "回复内容为空!", Toast.LENGTH_SHORT).show();//非空判断 isComment = true; setBaseState(); return; }else { if (toNickName.equals(nickName)) { Toast.makeText(ActivityDetailsActivity.this, "不能回复自己!", Toast.LENGTH_SHORT).show(); isComment = true; setBaseState(); return; } else { if (type==CALL_BACK_TYPE_TWO){//2号类型回复 int callBackPOS=CallBackAdapter.callBackToPOS; int commentID = commentList.get(callBackPOS).getCommentID(); int toID = CallBackAdapter.callBackToID; ArrayList<CallBackDetailEntity> detailMSGList = CallBackAdapter.MSGS; CallBackUtil.handleBack(token, commentID, Integer.valueOf(userId), toID, comment, detailMSGList, handler, HANDLE_MAIN_USER_BACK, nickName, toNickName); isComment = true; autoRefresh(); }else{//1号类型回复 int commentID = commentList.get(notifyPos).getCommentID(); etCallBack.setText(""); CallBackUtil.handleBack(token, commentID, Integer.valueOf(userId), -1, comment, detailMSGs, handler, HANDLE_MAIN_USER_BACK, nickName, ""); isComment = true; autoRefresh(); } } } } } } private void setBaseState(){ etCallBack.setHint("说点什么吧。。。"); etCallBack.setText(""); etCallBack.setTextColor(Color.parseColor("#999999")); InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==100){ if(resultCode==10){ View view=getLayoutInflater().inflate(R.layout.apply_dialog, null); final Dialog dialog = new Dialog(ActivityDetailsActivity.this, R.style.transparentFrameWindowStyle); ImageView im_cancel=(ImageView) view.findViewById(R.id.im_cancel); im_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); } } } @Override protected void onResume() { super.onResume(); handleData(); etCallBack.setHint("说点什么吧。。。"); etCallBack.setText(""); etCallBack.setTextColor(Color.parseColor("#999999")); if (commentList.size()!=0){ commentList.clear(); setCallBackView(); } getSignUpInfo(); } @Override public void onRefresh() { setCallBackView(); handleData(); etCallBack.setHint("说点什么吧。。。"); etCallBack.setText(""); etCallBack.setTextColor(Color.parseColor("#999999")); new Handler().postDelayed(new Runnable() { @Override public void run() { // 停止刷新 reflesh.setRefreshing(false); } }, 1000); } }
45.304619
191
0.595359
1c6d80fe5c159011c3c65f2c091f23a1ca1ca2e3
4,031
package com.atul.mangatain.ui.setting; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import androidx.appcompat.app.AppCompatDelegate; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.atul.mangatain.MTConstants; import com.atul.mangatain.MTPreferences; import com.atul.mangatain.R; import com.atul.mangatain.ui.setting.adapter.AccentAdapter; public class SettingFragment extends Fragment implements View.OnClickListener { private RecyclerView accentView; private LinearLayout chipLayout; private ImageView currentThemeMode; public SettingFragment() { } public static SettingFragment newInstance() { return new SettingFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_setting, container, false); accentView = view.findViewById(R.id.accent_view); chipLayout = view.findViewById(R.id.chip_layout); currentThemeMode = view.findViewById(R.id.current_theme_mode); LinearLayout accentOption = view.findViewById(R.id.accent_option); LinearLayout themeModeOption = view.findViewById(R.id.theme_mode_option); LinearLayout githubOption = view.findViewById(R.id.github_option); setCurrentThemeMode(); accentView.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.HORIZONTAL, false)); accentView.setAdapter(new AccentAdapter(getActivity())); accentOption.setOnClickListener(this); themeModeOption.setOnClickListener(this); githubOption.setOnClickListener(this); view.findViewById(R.id.night_chip).setOnClickListener(this); view.findViewById(R.id.light_chip).setOnClickListener(this); view.findViewById(R.id.auto_chip).setOnClickListener(this); return view; } private void setCurrentThemeMode() { int mode = MTPreferences.getThemeMode(requireActivity().getApplicationContext()); if (mode == AppCompatDelegate.MODE_NIGHT_NO) currentThemeMode.setImageResource(R.drawable.ic_theme_mode_light); else if (mode == AppCompatDelegate.MODE_NIGHT_YES) currentThemeMode.setImageResource(R.drawable.ic_theme_mode_night); else currentThemeMode.setImageResource(R.drawable.ic_theme_mode_auto); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.accent_option) { int visibility = (accentView.getVisibility() == View.VISIBLE) ? View.GONE : View.VISIBLE; accentView.setVisibility(visibility); } else if(id == R.id.github_option){ startActivity(new Intent( Intent.ACTION_VIEW, Uri.parse(MTConstants.GITHUB_REPO_URL) )); } else if (id == R.id.theme_mode_option) { int mode = chipLayout.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE; chipLayout.setVisibility(mode); } else if (id == R.id.night_chip) selectTheme(AppCompatDelegate.MODE_NIGHT_YES); else if (id == R.id.light_chip) selectTheme(AppCompatDelegate.MODE_NIGHT_NO); else if (id == R.id.auto_chip) selectTheme(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM); } private void selectTheme(int theme) { AppCompatDelegate.setDefaultNightMode(theme); MTPreferences.storeThemeMode(requireActivity().getApplicationContext(), theme); } }
33.87395
108
0.69933
4becdbae77ac995c42d30d88f3ac1c6253096881
4,802
// ********************************************************************** // This file was generated by a TAF parser! // TAF version 3.0.0.34 by WSRD Tencent. // Generated from `/usr/local/resin_system.mqq.com/webapps/communication/taf/upload/noahyang/connServiceInvalid.jce' // ********************************************************************** package com.qq.jce.WCS; public final class ComponentUnitInfo extends com.qq.taf.jce.JceStruct implements java.lang.Cloneable { public String className() { return "WCS.ComponentUnitInfo"; } public String fullClassName() { return "com.qq.jce.WCS.ComponentUnitInfo"; } public String sUrl = ""; public String sMd5 = ""; public String sName = ""; public String sVersion = ""; public String sFeature = ""; public String sDependence = ""; public String getSUrl() { return sUrl; } public void setSUrl(String sUrl) { this.sUrl = sUrl; } public String getSMd5() { return sMd5; } public void setSMd5(String sMd5) { this.sMd5 = sMd5; } public String getSName() { return sName; } public void setSName(String sName) { this.sName = sName; } public String getSVersion() { return sVersion; } public void setSVersion(String sVersion) { this.sVersion = sVersion; } public String getSFeature() { return sFeature; } public void setSFeature(String sFeature) { this.sFeature = sFeature; } public String getSDependence() { return sDependence; } public void setSDependence(String sDependence) { this.sDependence = sDependence; } public ComponentUnitInfo() { } public ComponentUnitInfo(String sUrl, String sMd5, String sName, String sVersion, String sFeature, String sDependence) { this.sUrl = sUrl; this.sMd5 = sMd5; this.sName = sName; this.sVersion = sVersion; this.sFeature = sFeature; this.sDependence = sDependence; } public boolean equals(Object o) { if(o == null) { return false; } ComponentUnitInfo t = (ComponentUnitInfo) o; return ( com.qq.taf.jce.JceUtil.equals(sUrl, t.sUrl) && com.qq.taf.jce.JceUtil.equals(sMd5, t.sMd5) && com.qq.taf.jce.JceUtil.equals(sName, t.sName) && com.qq.taf.jce.JceUtil.equals(sVersion, t.sVersion) && com.qq.taf.jce.JceUtil.equals(sFeature, t.sFeature) && com.qq.taf.jce.JceUtil.equals(sDependence, t.sDependence) ); } public int hashCode() { try { throw new Exception("Need define key first!"); } catch(Exception ex) { ex.printStackTrace(); } return 0; } public java.lang.Object clone() { java.lang.Object o = null; try { o = super.clone(); } catch(CloneNotSupportedException ex) { assert false; // impossible } return o; } public void writeTo(com.qq.taf.jce.JceOutputStream _os) { _os.write(sUrl, 0); _os.write(sMd5, 1); _os.write(sName, 2); _os.write(sVersion, 3); if (null != sFeature) { _os.write(sFeature, 4); } if (null != sDependence) { _os.write(sDependence, 5); } } public void readFrom(com.qq.taf.jce.JceInputStream _is) { this.sUrl = _is.readString(0, true); this.sMd5 = _is.readString(1, true); this.sName = _is.readString(2, true); this.sVersion = _is.readString(3, true); this.sFeature = _is.readString(4, false); this.sDependence = _is.readString(5, false); } public void display(java.lang.StringBuilder _os, int _level) { com.qq.taf.jce.JceDisplayer _ds = new com.qq.taf.jce.JceDisplayer(_os, _level); _ds.display(sUrl, "sUrl"); _ds.display(sMd5, "sMd5"); _ds.display(sName, "sName"); _ds.display(sVersion, "sVersion"); _ds.display(sFeature, "sFeature"); _ds.display(sDependence, "sDependence"); } public void displaySimple(java.lang.StringBuilder _os, int _level) { com.qq.taf.jce.JceDisplayer _ds = new com.qq.taf.jce.JceDisplayer(_os, _level); _ds.displaySimple(sUrl, true); _ds.displaySimple(sMd5, true); _ds.displaySimple(sName, true); _ds.displaySimple(sVersion, true); _ds.displaySimple(sFeature, true); _ds.displaySimple(sDependence, false); } }
23.890547
122
0.553936
2e4ecd404f41abf136b51cb3f6f00697c9bd21f4
2,677
package com.fivium.scriptrunner2.script.parser; import com.fivium.scriptrunner2.ex.ExInternal; import com.fivium.scriptrunner2.ex.ExParser; import com.fivium.scriptrunner2.script.parser.ScriptParser.EscapeDelimiter; /** * Segment of a SQL statement which is "escaped" in some way, i.e. part of a comment block or within quotation marks. */ class EscapedTextSegment extends ScriptSegment { /** The delimiter string which is encapsulating this escaped text */ EscapeDelimiter mEscapeDelimiter; EscapedTextSegment(EscapeDelimiter pEscapeDelimiter, int pStartIndex){ super(pStartIndex); mEscapeDelimiter = pEscapeDelimiter; } ScriptSegment consumeBuffer(String pBuffer) throws ExParser { //Sanity check that the buffer starts with the correct sequence if(pBuffer.indexOf(mEscapeDelimiter.mStartSequence) != 0){ //This is an internal error, this method should not have been called if the buffer is not in the correct state throw new ExInternal("Sequence " + mEscapeDelimiter + " should start at position 0"); } //Find the corresponding terminating sequence int lEndPosition = pBuffer.indexOf(mEscapeDelimiter.mEndSequence, 1); int lEndEscSeqLength = mEscapeDelimiter.mEndSequence.length(); //If the remaining string doesn't contain this segment's termination sequence, that is a problem if(lEndPosition == -1){ if(mEscapeDelimiter.mRequiresEndDelimiter){ throw new ExParser("Unterminated escape sequence " + mEscapeDelimiter); } else { //For "--" sequence, end of file counts as a terminator lEndPosition = pBuffer.length()-1; } } //Record the contents of this segment setContents(pBuffer.substring(mEscapeDelimiter.mStartSequence.length(), lEndPosition)); //Return a new unescaped segment which will start reading from the end of this segment return new UnescapedTextSegment(lEndPosition + lEndEscSeqLength); } void serialiseTo(StringBuilder pBuilder) { pBuilder.append(mEscapeDelimiter.mStartSequence); pBuilder.append(getContents()); pBuilder.append(mEscapeDelimiter.mEndSequence); } /** * Gets the delimiter string which is encapsulating this escaped text. * @return Escape delimiter for this text. */ EscapeDelimiter getEscapeDelimiter() { return mEscapeDelimiter; } /** * Tests if this segment is a single or multi line comment. * @return True if this segment represents a SQL comment. */ public boolean isComment(){ return mEscapeDelimiter == EscapeDelimiter.COMMENT_MULTILINE || mEscapeDelimiter == EscapeDelimiter.COMMENT_SINGLELINE; } }
35.693333
123
0.732536
66fcdb4336280bce4ec6576e8b3855804de17e47
141
package org.camunda.bpm.camel.spring.util; public interface LogService { public void debug(Object msg); public void info(Object msg); }
20.142857
42
0.758865
105c1b790c2518425081bdf3e719aa4531c8590a
5,208
package com.rei.ropeteam.discovery; import static java.util.stream.Collectors.toList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import fi.iki.elonen.NanoHTTPD; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.ReceiverAdapter; import org.jgroups.logging.LogFactory; import org.jgroups.protocols.FD_ALL; import org.jgroups.protocols.FD_SOCK; import org.jgroups.protocols.FRAG2; import org.jgroups.protocols.TCP_NIO2; import org.jgroups.protocols.UNICAST3; import org.jgroups.protocols.pbcast.GMS; import org.jgroups.protocols.pbcast.NAKACK2; import org.jgroups.protocols.pbcast.STABLE; import org.jgroups.stack.IpAddress; import org.jgroups.util.ExtendedUUID; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.rei.ropeteam.JgroupsLogFactoryAdapter; public class ExternalJsonFileDiscoveryTest { private CountDownLatch countDownLatch = new CountDownLatch(9); static { LogFactory.setCustomLogFactory(new JgroupsLogFactoryAdapter()); } @Test public void findMembers() throws Exception { ClusterMember a = createMember("a"); ClusterMember b = createMember("b"); ClusterMember c = createMember("c"); ClusterMembers members = new ClusterMembers(); members.setMembers(Arrays.asList(a, b, c)); JsonServer server = new JsonServer(members); server.start(); List<JChannel> channels = members.getMembers().parallelStream() .map(m -> createChannel(server.getListeningPort(), m.getPort(), m.getHost())) .collect(toList()); channels.forEach(ch -> { System.out.println(ch.getAddressAsString() + " View:" + ch.getViewAsString()); assertEquals(3, ch.getView().getMembers().size()); try { ch.send(null, "test message"); Thread.sleep(50); } catch (Exception e) { throw new RuntimeException(e); } }); boolean success = countDownLatch.await(1, TimeUnit.SECONDS); assertTrue("only received " + countDownLatch.getCount() + " messages!", success); } private JChannel createChannel(int serverPort, int port, String host) { try { ClusterMemberService service = new ClusterMemberService("http://127.0.0.1:" + serverPort); service.setAddressLookup(this::mockAddressLookup); // DynamicPortTcpNio2 tcp = new DynamicPortTcpNio2(service); TCP_NIO2 tcp = new TCP_NIO2(); tcp.setBindAddress(InetAddress.getLoopbackAddress()); tcp.setBindPort(port); tcp.setPortRange(1); JChannel channel = new JChannel(tcp, new ExternalJsonFileDiscovery(service), new FD_SOCK(), new FD_ALL(), new NAKACK2(), new UNICAST3(), new STABLE(), new GMS().joinTimeout(1000), new FRAG2().fragSize(8000)); channel.addAddressGenerator(() -> ExtendedUUID.randomUUID(host)); channel.receiver(new ReceiverAdapter() { @Override public void receive(Message msg) { countDownLatch.countDown(); } }); channel.connect("test-cluster"); return channel; } catch (Exception e) { throw new RuntimeException(e); } } private IpAddress mockAddressLookup(ClusterMember member) { return getLocalIpAddress(member.getPort()); } private IpAddress getLocalIpAddress(int port) { try { return new IpAddress("127.0.0.1", port); } catch (UnknownHostException e) { return null; } } private ClusterMember createMember(String host) throws IOException { ClusterMember member = new ClusterMember(); member.setHost(host); member.setPort(findOpenPort()); return member; } private int findOpenPort() throws IOException { try (ServerSocket s = new ServerSocket(0)) { return s.getLocalPort(); } } private static class JsonServer extends NanoHTTPD { private String stringContent; public JsonServer(Object content) throws JsonProcessingException { super(0); this.stringContent = new ObjectMapper().writeValueAsString(content); } @Override public Response serve(IHTTPSession session) { return newFixedLengthResponse(stringContent); } } }
34.263158
102
0.615207
ba0b22e02b1add15fe0ff34848e3183050b9e34d
6,618
package org.ico.main; import org.neo.smartcontract.framework.services.neo.TriggerType; import org.neo.smartcontract.framework.services.system.ExecutionEngine; import java.math.BigInteger; import org.ico.token.NEP5Template; import org.ico.token.TemplateToken; import org.neo.smartcontract.framework.Helper; import org.neo.smartcontract.framework.SmartContract; import org.neo.smartcontract.framework.services.neo.Runtime; import org.neo.smartcontract.framework.services.neo.Storage; import org.neo.smartcontract.framework.services.neo.Transaction; import org.neo.smartcontract.framework.services.neo.TransactionOutput; public class ICOTemplate extends SmartContract { /** * The EPOC start time for the ICO. The associated time unit is seconds */ private final static long ICO_START_TIME = 1521003600; /** * The EPOC end time for the ICO. The associated time unit is seconds */ private final static long ICO_END_TIME = 1523682000; /** * The Entry point for the ICO Smart Contract. The neoj neo-compiler looks * for a method named: Main with an uppercase M. */ public static Object Main(String operation, Object[] args) { TriggerType trigger = Runtime.trigger(); if (trigger == TriggerType.Verification) { boolean isOwner = Runtime.checkWitness(TemplateToken.getOwner()); if (isOwner) { return true; } return false; } else if (trigger == TriggerType.Application) { if (operation.equals("deploy")) { return deploy(); } else if (operation.equals("mintTokens")) { return mintTokens(); } else if (operation.equals(NEP5Template.TOTAL_SUPPLY)) { return NEP5Template.totalSupply(); } else if (operation.equals(NEP5Template.NAME)) { return NEP5Template.name(); } else if (operation.equals(NEP5Template.SYMBOL)) { return NEP5Template.symbol(); } else if (operation.equals(NEP5Template.DECIMALS)) { return NEP5Template.decimalsString(); } else if (operation.equals(NEP5Template.BALANCE_OF)) { if (args.length < 1) { Runtime.log("No account argument-No action"); return false; } byte[] account = Helper.asByteArray((String) args[0]); return NEP5Template.balanceOf(account); } else if (operation.equals(NEP5Template.TRANSFER)) { if (args.length != 3) { Runtime.log("Insufficient number of arguments-No action"); return false; } byte[] from = Helper.asByteArray((String) args[0]); byte[] to = Helper.asByteArray((String) args[1]); BigInteger amount = BigInteger.valueOf(Long.valueOf((String) args[2])); return NEP5Template.transfer(from, to, amount); } } return false; } public static Object deploy() { if (getTotalSupply().length != 0) { Runtime.log("Insufficient token supply-No action"); return false; } Storage.put(Storage.currentContext(), TemplateToken.getOwner(), TemplateToken.getPreIcoCap()); Storage.put(Storage.currentContext(), NEP5Template.TOTAL_SUPPLY, TemplateToken.getPreIcoCap()); return true; } public static Object mintTokens() { byte[] sender = getSender(); if (sender.length == 0) { Runtime.log("Asset is not neo-No action"); return false; } // The current exchange rate between ICO tokens and Neo during the token // swap period BigInteger swapRate = currentSwapRate(); if (swapRate.equals(BigInteger.ZERO)) { Runtime.log("Crowd funding failure-No action"); return false; } BigInteger contributionAmount = getContributionAmount(); BigInteger tokenTransferAmount = currentSwapToken(sender, contributionAmount, swapRate); if (tokenTransferAmount.equals(BigInteger.ZERO)) { Runtime.log("Zero token transfer amount-No action"); return false; } byte[] senderBalanceByteArray = Storage.get(Storage.currentContext(), sender); BigInteger senderBalance = new BigInteger(senderBalanceByteArray); BigInteger postTransferAmount = senderBalance.add(tokenTransferAmount); Storage.put(Storage.currentContext(), sender, postTransferAmount); BigInteger tokenAndSupply = tokenTransferAmount.add(NEP5Template.totalSupply()); Storage.put(Storage.currentContext(), NEP5Template.TOTAL_SUPPLY, tokenAndSupply); return true; } private static BigInteger currentSwapRate() { long icoDuration = ICO_END_TIME - ICO_START_TIME; long now = Runtime.time(); long time = now - ICO_START_TIME; if (time < 0) { return BigInteger.ZERO; } else if (time < icoDuration) { return TemplateToken.getBasicRate(); } return BigInteger.ZERO; } private static BigInteger getContributionAmount() { Transaction tx = (Transaction) ExecutionEngine.scriptContainer(); TransactionOutput[] outputs = tx.outputs(); BigInteger contributionAmount = BigInteger.ZERO; for (TransactionOutput transaction : outputs) { if (transaction.scriptHash() == getReceiver() && transaction.assetId() == neoAssetId()) { BigInteger transactionAmount = BigInteger.valueOf(transaction.value()); contributionAmount = contributionAmount.add(transactionAmount); } } return contributionAmount; } private static BigInteger currentSwapToken(byte[] sender, BigInteger contributedAmount, BigInteger swapRate) { BigInteger tokenAmount = contributedAmount.divide(TemplateToken.getDecimals()).multiply(swapRate); BigInteger tokenBalance = TemplateToken.getTotalAmount().subtract(NEP5Template.totalSupply()); if (tokenBalance.compareTo(BigInteger.ZERO) <= 0) { return BigInteger.ZERO; } else if (tokenBalance.compareTo(tokenAmount) < 0) { tokenAmount = tokenBalance; } return tokenAmount; } /** * @return smart contract script hash */ private static byte[] getReceiver() { return ExecutionEngine.executingScriptHash(); } private static byte[] getSender() { Transaction tx = (Transaction) ExecutionEngine.scriptContainer(); TransactionOutput[] reference = tx.references(); for (TransactionOutput output : reference) { if (output.assetId() == neoAssetId()) { return output.scriptHash(); } } return Helper.asByteArray(""); } private static byte[] getTotalSupply() { return Storage.get(Storage.currentContext(), NEP5Template.TOTAL_SUPPLY); } private static byte[] neoAssetId() { byte[] assetId = new byte[] { (byte) 155, (byte) 124, (byte) 255, (byte) 218, (byte) 166, (byte) 116, (byte) 190, (byte) 174, (byte) 15, (byte) 147, (byte) 14, (byte) 190, (byte) 96, (byte) 133, (byte) 175, (byte) 144, (byte) 147, (byte) 229, (byte) 254, (byte) 86, (byte) 179, (byte) 74, (byte) 92, (byte) 34, (byte) 12, (byte) 205, (byte) 207, (byte) 110, (byte) 252, (byte) 51, (byte) 111, (byte) 197 }; return assetId; } }
32.441176
111
0.721064
1cfd75cfc25fc2119cc9e762f2c9cf65fde894b2
1,274
/* * ConnectionListener.java * Created on 2011-08-24 * * Copyright (c) Verax Systems 2011. * All rights reserved. * * This software is furnished under a license. Use, duplication, * disclosure and all other uses are restricted to the rights * specified in the written license agreement. */ package ipmi.connection; import ipmi.coding.commands.ResponseData; /** * Interface for the {@link Connection} listener. */ public interface ConnectionListener { /** * Notifies the {@link ConnectionListener}s of the one of the following * events: <li>response to the request tagged with id arrived <li>request * tagged with id timed out * * @param responseData * - {@link ResponseData} specific for the request if it was * completed successfully, null if it timed out or an error * occured during decoding. * @param handle * - the id of the connection that received the message * @param id * - tag of the request-response pair * @param exception * - null if everything went correctly or timeout occured, * contains exception that occured during decoding if it failed. */ void notify(ResponseData responseData, int handle, int id, Exception exception); }
31.073171
76
0.682104
f1c37af87468176cfe65bca8358f81d60b7118f2
1,767
package org.bson.codecs.configuration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bson.codecs.Codec; public final class CodecRegistries { public static CodecRegistry fromCodecs(Codec<?>... codecs) { return fromCodecs(Arrays.asList(codecs)); } public static CodecRegistry fromCodecs(List<? extends Codec<?>> codecs) { return fromProviders(new CodecProvider[] { new MapOfCodecsProvider(codecs) }); } public static CodecRegistry fromProviders(CodecProvider... providers) { return fromProviders(Arrays.asList(providers)); } public static CodecRegistry fromProviders(List<? extends CodecProvider> providers) { return new ProvidersCodecRegistry(providers); } public static CodecRegistry fromRegistries(CodecRegistry... registries) { return fromRegistries(Arrays.asList(registries)); } public static CodecRegistry fromRegistries(List<? extends CodecRegistry> registries) { List<CodecProvider> providers = new ArrayList(); for (CodecRegistry registry : registries) { providers.add(providerFromRegistry(registry)); } return new ProvidersCodecRegistry(providers); } private static CodecProvider providerFromRegistry(CodecRegistry innerRegistry) { if ((innerRegistry instanceof CodecProvider)) { return (CodecProvider)innerRegistry; } new CodecProvider() { public <T> Codec<T> get(Class<T> clazz, CodecRegistry outerRregistry) { try { return val$innerRegistry.get(clazz); } catch (CodecConfigurationException e) {} return null; } }; } private CodecRegistries() {} }
11.78
86
0.678551
eef12d920ea2d54815d7d525ea56d6fe7e373497
490
package com.zlsoft.pj.wx.api; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import tk.mybatis.spring.annotation.MapperScan; /** * 主启动类 * @author dp * @version 1.0.0 * @date 2020-02-28 10:21 */ @SpringBootApplication @MapperScan("com.zlsoft.pj.wx.api.mapper") public class PjWxApiApplication { public static void main(String[] args) { SpringApplication.run(PjWxApiApplication.class, args); } }
24.5
68
0.75102
97d13a5a923c16055d2f88bfc150a06c34ce5a7e
775
package com.uchicom.h2m; import java.sql.SQLException; import org.h2.tools.Server; public class TcpServerMain { private static Server tcpServer; private static boolean alive ; public static void main(String[] args) { try { tcpServer = Server.createTcpServer(args).start(); System.out.println("tcp server start"); alive = true; while (alive) { Thread.sleep(1000); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void shutdown() { if (tcpServer != null) { tcpServer.stop(); System.out.println("tcp server stop"); } alive = false; } }
21.527778
53
0.646452
90dca48441c16998782e4c3a8fcc17292a303560
9,130
/* * Copyright (c) [2021] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ import java.lang.reflect.Field; import java.util.ArrayList; import com.huawei.ark.annotation.*; public class RCPermanentThread2 { static { System.loadLibrary("jniTestHelper"); } public static void main(String[] args) throws InterruptedException { rc_testcase_main_wrapper(); rc_testcase_main_wrapper2(); } private static void rc_testcase_main_wrapper() throws InterruptedException { RCPermanentTest rcPermanentTest = new RCPermanentTest(); RCPermanentTest rcPermanentTest2 = new RCPermanentTest(); RCPermanentTest rcPermanentTest3 = new RCPermanentTest(); RCPermanentTest rcPermanentTest4 = new RCPermanentTest(); RCPermanentTest rcPermanentTest5 = new RCPermanentTest(); rcPermanentTest.start(); rcPermanentTest.join(); rcPermanentTest2.start(); rcPermanentTest2.join(); rcPermanentTest3.start(); rcPermanentTest3.join(); rcPermanentTest4.start(); rcPermanentTest4.join(); rcPermanentTest5.start(); rcPermanentTest5.join(); // rcPermanentTest.join(); // rcPermanentTest2.join(); // rcPermanentTest3.join(); // rcPermanentTest4.join(); // rcPermanentTest5.join(); if (rcPermanentTest.check() && rcPermanentTest2.check() && rcPermanentTest3.check() && rcPermanentTest4.check() && rcPermanentTest5.check()) { System.out.println("ExpectResult"); } else { System.out.println("error"); System.out.println("rcPermanentTest.check() :" + rcPermanentTest.check()); System.out.println("rcPermanentTest2.check() :" + rcPermanentTest2.check()); System.out.println("rcPermanentTest3.check() :" + rcPermanentTest3.check()); System.out.println("rcPermanentTest4.check() :" + rcPermanentTest4.check()); System.out.println("rcPermanentTest5.check() :" + rcPermanentTest5.check()); } } private static void rc_testcase_main_wrapper2() throws InterruptedException { RCUnownedTest rcUnownedTest = new RCUnownedTest(); RCUnownedTest rcUnownedTest2 = new RCUnownedTest(); RCUnownedTest rcUnownedTest3 = new RCUnownedTest(); RCUnownedTest rcUnownedTest4 = new RCUnownedTest(); RCUnownedTest rcUnownedTest5 = new RCUnownedTest(); rcUnownedTest.start(); rcUnownedTest2.start(); rcUnownedTest3.start(); rcUnownedTest4.start(); rcUnownedTest5.start(); rcUnownedTest.join(); rcUnownedTest2.join(); rcUnownedTest3.join(); rcUnownedTest4.join(); rcUnownedTest5.join(); } } class RCPermanentTest extends Thread { public boolean checkout; public static native boolean isHeapObject(Object obj); public static native int refCount(Object obj); public static int checkNum = 0; static Object owner; static boolean checkRC(Object obj) { int rc1 = refCount(obj); owner = obj; int rc2 = refCount(obj); owner = null; int rc3 = refCount(obj); if (rc1 != rc3) { throw new RuntimeException("rc incorrect!"); } if (rc1 == rc2 && rc2 == rc3) { //如果相等,说明annotation生效,没有经过RC处理 return false; } else { return true; } //System.out.printf("rc:%-5s heap:%-5s %s%n", !skipRC, isHeapObject(obj), title); } /* 验证new int @Permanent [8] */ static void method1(Object obj) { obj = new int@Permanent[8]; boolean result1 = checkRC(obj); if (result1 == false && isHeapObject(obj) == false) { checkNum++; } else { System.out.println("error in new int @Permanent [8];in method1"); } } /* 验证new int [8] */ static void method2(Object obj) { obj = new int[8]; boolean result1 = checkRC(obj); if (result1 == true && isHeapObject(obj) == true) { checkNum++; } else { System.out.println("error in new int [8];in method2"); } } /* 验证new @Permanent int[8] */ static void method3(Object obj) { obj = new @Permanent int[1]; boolean result1 = checkRC(obj); if (result1 == false && isHeapObject(obj) == false) { checkNum++; } else { System.out.println("error in new @Permanent int[8];in method3"); } } /* 验证new Integer @Permanent [10] */ static void method4(Object obj) { Integer[] arr = new Integer@Permanent[10]; boolean result1 = checkRC(obj); noleak.add(arr); // let leak check happy arr[0] = new Integer(10000); arr[9] = new Integer(20000); if (result1 == false && isHeapObject(obj) == false) { checkNum++; } else { System.out.println("error in new Integer @Permanent [10];in method4"); } } /* 验证new @Permanent Integer [10] */ static void method5(Object obj) { Integer[] arr = new @Permanent Integer[10]; boolean result1 = checkRC(obj); noleak.add(arr); // let leak check happy arr[0] = new Integer(10000); arr[9] = new Integer(20000); if (result1 == false && isHeapObject(obj) == false) { checkNum++; } else { System.out.println("error in new @Permanent Integer [10];in method5"); } } /* 验证new Integer[10]; */ static void method6(Object obj) { obj = new Integer[10]; boolean result1 = checkRC(obj); if (result1 == true && isHeapObject(obj) == true) { checkNum++; } else { System.out.println("error in new Integer[10];in method6"); System.out.println("checkRC(obj):" + result1 + " isHeapObject(obj):" + isHeapObject(obj)); } } /* 验证new @Permanent ArrayList[]{}; */ static void method7(Object obj) { obj = new @Permanent ArrayList[]{}; boolean result1 = checkRC(obj); if (result1 == false && isHeapObject(obj) == false) { checkNum++; } else { System.out.println("error in new @Permanent ArrayList[]{};in method7"); } } /* 验证new ArrayList @Permanent []{}; */ static void method8(Object obj) { obj = new ArrayList@Permanent[]{}; boolean result1 = checkRC(obj); if (result1 == false && isHeapObject(obj) == false) { checkNum++; } else { System.out.println("error in new ArrayList @Permanent []{};in method8"); } } /* 验证new ArrayList []{}; */ static void method9(Object obj) { obj = new ArrayList[]{}; boolean result1 = checkRC(obj); if (result1 == true && isHeapObject(obj) == true) { checkNum++; } else { System.out.println("error in new ArrayList []{}; method9"); } } static ArrayList<Object> noleak = new ArrayList<>(); public void run( ) { checkNum = 0; Object obj = null; method1(obj); method2(obj); method3(obj); method4(obj); method5(obj); method6(obj); method7(obj); method8(obj); method9(obj); // System.out.println(checkNum); if (checkNum == 9) { checkout = true; } else { checkout = false; System.out.println("checkout== false,checkNum:"+checkNum); } } public boolean check() { return checkout; } } class RCUnownedTest extends Thread { public void run() { new Test_A().test(); } } class Test_A { Test_B bb; public void test() { setReferences(); System.runFinalization(); } private void setReferences() { Test_A ta = new Test_A(); ta.bb = new Test_B(); //ta.bb.aa = ta; try { Field m = Test_B.class.getDeclaredField("aa"); m.set(ta.bb, ta); Test_A a_temp = (Test_A) m.get(ta.bb); if (a_temp != ta) { System.out.println("error"); } //Field m1 = Test_B.class.getDeclaredField("a1"); //m1.set(null, ta); } catch (Exception e) { System.out.println(e); } } } class Test_B { @Unowned Test_A aa; // add volatile will crash // static Test_A a1; protected void finalize() { System.out.println("ExpectResult"); } }
30.740741
150
0.571632
3d07a9a09078d9420f4e1d75badafe17802afcf6
109
/** * */ package org.geek.pipe.api; /** * @author haichuan * 2012-2-2 */ public enum RequestType { }
8.384615
26
0.568807
46457afdc06b5104c533749674c7cb052a28ea3d
972
package com.felix.unbiz.json.rpc.server.bo; import com.felix.unbiz.json.rpc.server.JsonRpcExporter; /** * ClassName: RpcRequest <br/> * Function: JsonRpc请求逻辑对象 * * @author wangxujin */ public class RpcRequest { /** * 服务接口以及实现定义 */ private JsonRpcExporter exporter; /** * 请求字节码 */ private byte[] request; /** * Creates a new instance of RpcRequest. * * @param exporter * @param request */ public RpcRequest(JsonRpcExporter exporter, byte[] request) { this.exporter = exporter; this.request = request; } public JsonRpcExporter getExporter() { return exporter; } public void setExporter(JsonRpcExporter exporter) { this.exporter = exporter; } public byte[] getRequest() { return request; } public void setRequest(byte[] request) { this.request = request; } }
19.44
66
0.575103
ad37a53840a13b99c6ea353753bcb19a36ec6b99
835
package Strategy; import java.util.Random; public class Penalty { private Jogador jogador; private int contagem = 0; public Penalty(Jogador jogador) { setStrategy(jogador); } public void setStrategy(Jogador jogador) { this.jogador = jogador; } private int getLadoDefesa() { Random rnd = new Random(); return rnd.nextInt(3) +1; //retorna 1, 2 ou 3 } public boolean cobrarPenalty() { System.out.println(String.format("--- Penalty %d ---", ++contagem)); int ladoChute = this.jogador.chutar(); // <== aqui se chama o método de JOGADOR int ladoDefesa = getLadoDefesa(); System.out.println(String.format("chute=%d defesa=%d", ladoChute, ladoDefesa)); return (ladoChute != ladoDefesa); //true = gol, false = defendeu } }
26.09375
88
0.621557
7191b0f45bc357252fb80de54dc3ed5d0b2e45a5
11,873
package com.krupatek.courier.view.rate; import com.krupatek.courier.model.Client; import com.krupatek.courier.model.Courier; import com.krupatek.courier.model.RateIntEntry; import com.krupatek.courier.service.ClientService; import com.krupatek.courier.service.CourierService; import com.krupatek.courier.service.NetworkService; import com.krupatek.courier.service.RateIntMasterService; import com.krupatek.courier.utils.ViewUtils; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.ButtonVariant; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.formlayout.FormLayout; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.select.Select; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.data.binder.Binder; import com.vaadin.flow.data.binder.ValidationException; import com.vaadin.flow.data.value.ValueChangeMode; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class RateIntEntryForm extends Div { private String selectedNetwork = "FEDEX"; private RateIntEntry rateIntEntry; public RateIntEntryForm( ClientService clientService, NetworkService networkService, CourierService courierService, RateIntMasterService rateIntMasterService, RateIntEntry rateIntEntry, UpdateRateIntEntry updateRateIntEntry){ super(); this.rateIntEntry = rateIntEntry; boolean isNewRateIntEntry = rateIntEntry.getRateIntMasterId() == null; Binder<RateIntEntry> binder = new Binder<>(); Dialog dialog = new Dialog(); HorizontalLayout horizontalLayout = new HorizontalLayout(); horizontalLayout.setPadding(true); horizontalLayout.setMargin(false); FormLayout formLayout = new FormLayout(); formLayout.setMaxWidth("30em"); formLayout.setResponsiveSteps( new FormLayout.ResponsiveStep("30em", 1)); formLayout.add(ViewUtils.addCloseButton(dialog), 12); Label title = new Label(); title.setSizeFull(); title.setText("Rate Entry Details"); formLayout.add(title, 1); // Client Name if(isNewRateIntEntry){ Select<String> clientSelect = new Select<>(); clientSelect.setLabel("Select Client Name : "); List<Client> clientList = clientService.findAll(); List<String> clientNameList = new ArrayList<>(); clientList.forEach(c -> clientNameList.add(c.getClientName())); clientSelect.setItems(clientNameList); binder.bind(clientSelect, RateIntEntry::getClientName, RateIntEntry::setClientName); formLayout.add(clientSelect, 1); // Zones ComboBox<String> zoneSelect = new ComboBox<>(); zoneSelect.setLabel("State Code : "); zoneSelect.setItems(getZones(selectedNetwork, networkService)); binder.bind(zoneSelect, RateIntEntry::getStateCode, RateIntEntry::setStateCode); formLayout.add(zoneSelect, 1); // POD Type Select<String> selectDocumentOrParcelType = new Select<>(); selectDocumentOrParcelType.setLabel("POD Type : "); selectDocumentOrParcelType.setItems("D", "P"); binder.bind(selectDocumentOrParcelType, RateIntEntry::getPodType, RateIntEntry::setPodType); formLayout.add(selectDocumentOrParcelType, 1); // Mode Select<String> modeSelect = new Select<>(); modeSelect.setLabel("Mode : "); modeSelect.setItems("S", "L", "A"); binder.bind(modeSelect, RateIntEntry::getMode, RateIntEntry::setMode); formLayout.add(modeSelect, 1); } else { TextField clientName = new TextField(); clientName.setLabel("Client Name : "); clientName.setValueChangeMode(ValueChangeMode.EAGER); formLayout.add(clientName, 1); binder.bind(clientName, RateIntEntry::getClientName, RateIntEntry::setClientName); clientName.setReadOnly(true); // State code TextField stateCode = new TextField(); stateCode.setLabel("State Code : "); stateCode.setValueChangeMode(ValueChangeMode.EAGER); formLayout.add(stateCode, 1); binder.bind(stateCode, RateIntEntry::getStateCode, RateIntEntry::setStateCode); stateCode.setReadOnly(true); // POD Type TextField podType = new TextField(); podType.setLabel("POD Type : "); podType.setValueChangeMode(ValueChangeMode.EAGER); formLayout.add(podType, 1); binder.bind(podType, RateIntEntry::getPodType, RateIntEntry::setPodType); podType.setReadOnly(true); // Mode TextField mode = new TextField(); mode.setLabel("Mode : "); mode.setValueChangeMode(ValueChangeMode.EAGER); formLayout.add(mode, 1); binder.bind(mode, RateIntEntry::getMode, RateIntEntry::setMode); mode.setReadOnly(true); } // From TextField from = new TextField(); from.setLabel("From : "); from.setValueChangeMode(ValueChangeMode.EAGER); formLayout.add(from, 1); binder.bind(from, c -> c.getFrom1().toString(), (c, t) -> c.setFrom1(Double.valueOf(t))); // to TextField to = new TextField(); to.setLabel("From : "); to.setValueChangeMode(ValueChangeMode.EAGER); formLayout.add(to, 1); binder.bind(to, c -> c.getTo1().toString(), (c, t) -> c.setTo1(Double.valueOf(t))); // Rate TextField rate = new TextField(); rate.setLabel("Rate : "); rate.setValueChangeMode(ValueChangeMode.EAGER); formLayout.add(rate, 1); binder.bind(rate, c -> c.getRate().toString(), (c, t) -> c.setRate(Integer.valueOf(t))); // Add Rate TextField addRate = new TextField(); addRate.setLabel("Add Rate : "); addRate.setValueChangeMode(ValueChangeMode.EAGER); formLayout.add(addRate, 1); binder.bind(addRate, c -> c.getAddRt().toString(), (c, t) -> c.setAddRt(Integer.valueOf(t))); // Add Weight TextField addWeight = new TextField(); addWeight.setLabel("Add Weight : "); addWeight.setValueChangeMode(ValueChangeMode.EAGER); formLayout.add(addWeight, 1); binder.bind(addWeight, c -> c.getAddWt().toString(), (c, t) -> c.setAddWt(Double.valueOf(t))); Button save = new Button("Save", event -> { try { binder.writeBean(this.rateIntEntry); if(isNewRateIntEntry) { rateIntEntry.setRateIntMasterId(rateIntMasterService.latestIntMasterId() + 1); RateIntEntry existingRateIntEntry = rateIntMasterService.findByClientNameAndStateCodeAndPodTypeAndMode( rateIntEntry.getClientName(), rateIntEntry.getStateCode(), rateIntEntry.getPodType(), rateIntEntry.getMode() ); if(existingRateIntEntry != null){ Notification.show("Rate is already defined for client "+rateIntEntry.getClientName()+ ", to party : "+ selectedNetwork+", state code : "+rateIntEntry.getStateCode()+", d/p : "+ rateIntEntry.getPodType()+", mode : "+rateIntEntry.getMode()); } else { rateIntMasterService.saveAndFlush(this.rateIntEntry); updateRateIntEntry.update(this.rateIntEntry); Notification.show("Rate entry saved successfully."); } } else { rateIntMasterService.saveAndFlush(this.rateIntEntry); updateRateIntEntry.update(this.rateIntEntry); Notification.show("Rate entry updated successfully."); // A real application would also save the updated person // using the application's backend } } catch (ValidationException e) { Notification.show("Person could not be saved, " + "please check error messages for each field."); } }); Button reset = new Button("Reset", event -> binder.readBean(this.rateIntEntry)); Button cancel = new Button("Cancel", event -> dialog.close()); if(!isNewRateIntEntry){ Button delete = new Button("Delete", event -> { try { binder.writeBean(this.rateIntEntry); rateIntMasterService.delete(this.rateIntEntry); updateRateIntEntry.update(this.rateIntEntry); Notification.show("Rate Entry deleted successfully for client " + rateIntEntry.getClientName() + ", to party : " + selectedNetwork + ", state code : " + rateIntEntry.getStateCode() + ", d/p : " + rateIntEntry.getPodType() + ", mode : " + rateIntEntry.getMode()); } catch (Exception e) { Notification.show("Rate could not be deleted for client " + rateIntEntry.getClientName() + ", to party : " + selectedNetwork + ", state code : " + rateIntEntry.getStateCode() + ", d/p : " + rateIntEntry.getPodType() + ", mode : " + rateIntEntry.getMode()); } dialog.close(); }); delete.addThemeVariants(ButtonVariant.LUMO_ERROR); HorizontalLayout actions = new HorizontalLayout(); actions.setAlignItems(HorizontalLayout.Alignment.END); actions.add(save, reset, cancel, delete); formLayout.add(actions, 1); } else { HorizontalLayout actions = new HorizontalLayout(); actions.setAlignItems(HorizontalLayout.Alignment.END); actions.add(save, reset, cancel); formLayout.add(actions, 1); } horizontalLayout.add(formLayout); dialog.add(horizontalLayout); dialog.open(); binder.readBean(rateIntEntry); } private Set<String> getNetworks(CourierService courierService) { return courierService.findAll().parallelStream().map(Courier::getCourierName).collect(Collectors.toSet()); } private Set<String> getZones(String zone, NetworkService networkService){ return networkService.findDistinctZonesForNetwork(zone); } }
39.70903
137
0.575676
928c6a6edec433481979334c951258e1d0c59d54
4,318
package org.bouncycastle.crypto.generators; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; import org.bouncycastle.crypto.KeyGenerationParameters; import org.bouncycastle.crypto.params.RSAKeyGenerationParameters; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; import org.bouncycastle.math.ec.WNafUtil; import java.math.BigInteger; /** * an RSA key pair generator. */ public class RSAKeyPairGenerator implements AsymmetricCipherKeyPairGenerator { private static final BigInteger ONE = BigInteger.valueOf(1); private RSAKeyGenerationParameters param; public void init(KeyGenerationParameters param) { this.param = (RSAKeyGenerationParameters)param; } public AsymmetricCipherKeyPair generateKeyPair() { BigInteger p, q, n, d, e, pSub1, qSub1, phi; // // p and q values should have a length of half the strength in bits // int strength = param.getStrength(); int qBitlength = strength >>> 1; int pBitlength = strength - qBitlength; int mindiffbits = strength / 3; int minWeight = strength >>> 2; e = param.getPublicExponent(); // TODO Consider generating safe primes for p, q (see DHParametersHelper.generateSafePrimes) // (then p-1 and q-1 will not consist of only small factors - see "Pollard's algorithm") p = chooseRandomPrime(pBitlength, e); // // generate a modulus of the required length // for (;;) { q = chooseRandomPrime(qBitlength, e); // p and q should not be too close together (or equal!) BigInteger diff = q.subtract(p).abs(); if (diff.bitLength() < mindiffbits) { continue; } // // calculate the modulus // n = p.multiply(q); if (n.bitLength() != strength) { // // if we get here our primes aren't big enough, make the largest // of the two p and try again // p = p.max(q); continue; } /* * Require a minimum weight of the NAF representation, since low-weight composites may * be weak against a version of the number-field-sieve for factoring. * * See "The number field sieve for integers of low weight", Oliver Schirokauer. */ if (WNafUtil.getNafWeight(n) < minWeight) { p = chooseRandomPrime(pBitlength, e); continue; } break; } if (p.compareTo(q) < 0) { phi = p; p = q; q = phi; } pSub1 = p.subtract(ONE); qSub1 = q.subtract(ONE); phi = pSub1.multiply(qSub1); // // calculate the private exponent // d = e.modInverse(phi); // // calculate the CRT factors // BigInteger dP, dQ, qInv; dP = d.remainder(pSub1); dQ = d.remainder(qSub1); qInv = q.modInverse(p); return new AsymmetricCipherKeyPair( new RSAKeyParameters(false, n, e), new RSAPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv)); } /** * Choose a random prime value for use with RSA * * @param bitlength the bit-length of the returned prime * @param e the RSA public exponent * @return a prime p, with (p-1) relatively prime to e */ protected BigInteger chooseRandomPrime(int bitlength, BigInteger e) { for (;;) { BigInteger p = new BigInteger(bitlength, 1, param.getRandom()); if (p.mod(e).equals(ONE)) { continue; } if (!p.isProbablePrime(param.getCertainty())) { continue; } if (!e.gcd(p.subtract(ONE)).equals(ONE)) { continue; } return p; } } }
28.038961
100
0.54516
a156e2c852bf64bcdc2ac4e57c5d9d8850f8a1ca
1,119
package Utilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class DriverFactory { public enum browserType { FIREFOX, CHROME, IE, //not implemented SAFARI //not implemented } public static WebDriver getDriver(browserType type){ WebDriver driver = null; String pathOfDrivers = System.getProperty("user.dir")+"/src/main/resource/"; switch (type){ case FIREFOX: System.setProperty("webdriver.gecko.driver", pathOfDrivers+"geckodriver"); driver = new FirefoxDriver(); break; case CHROME: System.setProperty("webdriver.chrome.driver", pathOfDrivers+"chromedriver"); driver = new ChromeDriver(); break; default: System.setProperty("webdriver.chrome.driver", pathOfDrivers+"chromedriver"); driver = new ChromeDriver(); break; } return driver; } }
30.243243
92
0.593387
11f69acf541aa7a1d11353bf5a9cc1e738403c29
446
package com.zeligsoft.base.zdl.staticapi.Constructs.impl; import com.zeligsoft.base.zdl.staticapi.Constructs.DomainSpecialization; public class DomainSpecializationImpl extends DomainNamedElementImpl implements DomainSpecialization { public DomainSpecializationImpl(org.eclipse.emf.ecore.EObject element) { super(element); } @Override public org.eclipse.uml2.uml.Class asClass() { return (org.eclipse.uml2.uml.Class) eObject(); } }
27.875
79
0.804933
e3d8572a788046285f05c306706f798a4251630c
6,404
package uk.ac.ebi.subs.ena.action; import org.apache.commons.io.IOUtils; import org.apache.xmlbeans.XmlException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.oxm.Marshaller; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import uk.ac.ebi.ena.sra.xml.ObjectType; import uk.ac.ebi.ena.sra.xml.SubmissionType; import uk.ac.ebi.subs.data.submittable.ENASubmittable; import uk.ac.ebi.subs.data.submittable.Submittable; import uk.ac.ebi.subs.validator.data.SingleValidationResult; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.*; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.*; import java.util.ArrayList; import java.util.List; public abstract class AbstractSubmittablesActionService<S extends Submittable,T extends ENASubmittable<S>> implements SubmittablesActionService<S> { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); Class<T> enaClass; protected Marshaller marshaller; protected String schemaName = null; static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); static DocumentBuilder documentBuilder; static TransformerFactory transformerFactory; StringBuilder xmlBuffer = new StringBuilder(); Boolean modify; static { try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } } public AbstractSubmittablesActionService(Marshaller marshaller, String schemaName,Class<T> enaClass) { this.marshaller = marshaller; this.schemaName = schemaName; this.enaClass = enaClass; } @Override public SubmissionType.ACTIONS.ACTION createActionXML(S[] submittableObject) { if (submittableObject != null) { modify = null; for (S submittable : submittableObject) { if (modify != null && modify.booleanValue() != submittable.isAccessioned()) { throw new IllegalArgumentException("Submittables must be ALL accessioned (for the MODIFY ACTION) or all un-accessioned (for the CREATE action)"); } modify = submittable.isAccessioned(); } final SubmissionType.ACTIONS.ACTION action = SubmissionType.ACTIONS.ACTION.Factory.newInstance(); if (modify) { final SubmissionType.ACTIONS.ACTION.MODIFY modifyAction = action.addNewMODIFY(); modifyAction.setSchema(uk.ac.ebi.ena.sra.xml.SubmissionType.ACTIONS.ACTION.MODIFY.Schema.Enum.forString(getSchemaName())); modifyAction.setSource(getSchemaName() + ".xml"); } else { final SubmissionType.ACTIONS.ACTION.ADD addAction = action.addNewADD(); addAction.setSchema(uk.ac.ebi.ena.sra.xml.SubmissionType.ACTIONS.ACTION.ADD.Schema.Enum.forString(getSchemaName())); addAction.setSource(getSchemaName() + ".xml"); } return action; } else { return null; } } @Override public String getSchemaName() { return schemaName; } protected Document getDocument (ENASubmittable submittable) throws IOException { final Document document = documentBuilder.newDocument(); marshaller.marshal(submittable,new DOMResult(document)); return document; } String getDocumentString (Node node) throws TransformerException { DOMSource domSource = new DOMSource(node); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } protected Document getDocument(final S[] submittableObject, List<SingleValidationResult> singleValidationResultList) throws IOException { final Document document = documentBuilder.newDocument(); Element rootElement = document.createElement(getSetElementName()); document.appendChild(rootElement); for (S submittable : submittableObject) { try { final T enaSubmittable = T.create(enaClass, submittable); if (singleValidationResultList != null) singleValidationResultList.addAll(enaSubmittable.getValidationResultList()); Document submittableDocument = getDocument(enaSubmittable); final Node node = document.importNode(submittableDocument.getFirstChild(), true); try { final String documentString = getDocumentString(node); logger.info(documentString); } catch (TransformerException e) { e.printStackTrace(); } rootElement.appendChild(node); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } } return document; } private InputStream nodeToInputStream(Node node) throws TransformerException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Result outputTarget = new StreamResult(outputStream); Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); t.transform(new DOMSource(node), outputTarget); return new ByteArrayInputStream(outputStream.toByteArray()); } @Override public InputStream getXMLInputStream(S[] submittables,List<SingleValidationResult> singleValidationResults) throws IOException, XmlException, TransformerException { if (submittables != null && submittables.length > 0) { return nodeToInputStream(getDocument(submittables,singleValidationResults)); } return null; } abstract String getSetElementName (); }
41.051282
168
0.686602
7a13893e436246e5d6ff9da02b4b1dd92cc615d2
2,781
/* * Copyright 2018 Timothy J Veil * * 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 veil.hdp.hive.jdbc.utils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; public class PropertyUtils { private static final Logger log = LogManager.getLogger(PropertyUtils.class); private static PropertyUtils instance; private final Properties properties; private PropertyUtils() throws IOException { properties = new Properties(); try (InputStream resourceAsStream = getClass().getResourceAsStream("/driver-config.properties")) { properties.load(resourceAsStream); } } public static PropertyUtils getInstance() { if (instance == null) { try { instance = new PropertyUtils(); } catch (IOException ioe) { log.error(ioe.getMessage(), ioe); } } return instance; } public static void printProperties(Properties properties) { StringBuilder builder = new StringBuilder("\n"); builder.append(" -------------------------------------------------------------\n"); List<String> strings = new ArrayList<>(properties.stringPropertyNames()); Collections.sort(strings); for (String key : strings) { if (StringUtils.containsIgnoreCase(key, "password")) { continue; } builder.append('\t').append(key).append(" : ").append(properties.getProperty(key)).append('\n'); } builder.append(" -------------------------------------------------------------\n"); log.debug(builder.toString()); } public String getValue(String key) { return properties.getProperty(key); } public int getIntValue(String key) { return Integer.parseInt(properties.getProperty(key)); } public String getValue(String key, String defaultValue) { return properties.getProperty(key, defaultValue); } }
29.903226
108
0.627472
c2e97960a43a9adc481987e8d6b506299ef50098
3,349
/* * Copyright 2014-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.rules; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.util.immutables.BuckStyleImmutable; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializable; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.google.common.base.Functions; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.immutables.value.Value; import java.io.IOException; /** * A JSON-serializable structure that gets passed to external test runners. * * NOTE: We're relying on the fact we're using POJOs here and that all the sub-types are * JSON-serializable already. Be careful that we don't break serialization when adding item * here. */ @Value.Immutable @BuckStyleImmutable abstract class AbstractExternalTestRunnerTestSpec implements JsonSerializable { /** * @return the build target of this rule. */ public abstract BuildTarget getTarget(); /** * @return a test-specific type string which classifies the test class, so the external runner * knows how to parse the output. */ public abstract String getType(); /** * @return the command the external test runner must invoke to run the test. */ public abstract ImmutableList<String> getCommand(); /** * @return environment variables the external test runner should provide for the test command. */ public abstract ImmutableMap<String, String> getEnv(); /** * @return test labels. */ public abstract ImmutableList<Label> getLabels(); /** * @return test contacts. */ public abstract ImmutableList<String> getContacts(); @Override public void serialize( JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("target", getTarget().toString()); jsonGenerator.writeStringField("type", getType()); jsonGenerator.writeObjectField("command", getCommand()); jsonGenerator.writeObjectField("env", getEnv()); jsonGenerator.writeObjectField( "labels", FluentIterable.from(getLabels()) .transform(Functions.toStringFunction()) .toList()); jsonGenerator.writeObjectField("contacts", getContacts()); jsonGenerator.writeEndObject(); } @Override public void serializeWithType( JsonGenerator jsonGenerator, SerializerProvider serializerProvider, TypeSerializer typeSerializer) throws IOException { serialize(jsonGenerator, serializerProvider); } }
31.59434
96
0.741117
ce7ac32de73a893091cf7b922812e0c903d6f37e
570
package org.firstinspires.ftc.teamcode.robot.outreach; import com.qualcomm.robotcore.hardware.DigitalChannel; public class outreachTouchSensorCatapult { private DigitalChannel catapultTouchSensor; public outreachTouchSensorCatapult (DigitalChannel cTS) { catapultTouchSensor = cTS; catapultTouchSensor.setMode(DigitalChannel.Mode.INPUT); } public boolean checkCatapultTouchSensor () { if (catapultTouchSensor.getState() == true) { return true; } else { return false; } } }
24.782609
63
0.682456
c1c66b519f03b0de909de5ffdf4468b2e0a0173b
2,359
package org.iton.messenger.api; import io.netty.buffer.ByteBuf; import org.iton.messenger.core.TLContext; import org.iton.messenger.core.TLObject; import java.io.IOException; import static org.iton.messenger.core.utils.StreamingUtils.*; public class TLChatFull extends TLObject { public static final int CLASS_ID = 0x630e61be; protected int id; protected ChatParticipants participants; protected Photo chat_photo; protected PeerNotifySettings notify_settings; public TLChatFull() { } public TLChatFull(int id, ChatParticipants participants, Photo chat_photo, PeerNotifySettings notify_settings) { this.id = id; this.participants = participants; this.chat_photo = chat_photo; this.notify_settings = notify_settings; } @Override public int getClassId() { return CLASS_ID; } public int getId() { return this.id; } public void setId(int value) { this.id = value; } public ChatParticipants getParticipants() { return this.participants; } public void setParticipants(ChatParticipants participants) { this.participants = participants; } public Photo getChatPhoto() { return this.chat_photo; } public void setChatPhoto(Photo chat_photo) { this.chat_photo = chat_photo; } public PeerNotifySettings getNotifySettings() { return this.notify_settings; } public void setNotifySettings(PeerNotifySettings notify_settings) { this.notify_settings = notify_settings; } @Override public void serializeBody(ByteBuf stream) throws IOException { writeInt(this.id, stream); writeTLObject(this.participants, stream); writeTLObject(this.chat_photo, stream); writeTLObject(this.notify_settings, stream); } @Override public void deserializeBody(ByteBuf stream, TLContext context) throws IOException { this.id = readInt(stream); this.participants = (ChatParticipants) readTLObject(stream, context); this.chat_photo = (Photo) readTLObject(stream, context); this.notify_settings = (PeerNotifySettings) readTLObject(stream, context); } @Override public String toString() { return "chatFull#630e61be"; } }
27.430233
116
0.676558
d3339eb3518f928b43c7bc9f85274ac84b5e07fe
3,502
package com.mobgen.halo.android.app.ui.chat; import android.app.Activity; import android.content.Intent; import android.graphics.Point; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.Display; import android.view.SurfaceView; import android.view.Window; import android.view.WindowManager; import com.google.android.gms.vision.barcode.Barcode; import com.google.android.gms.vision.barcode.BarcodeDetector; import com.mobgen.halo.android.app.R; import com.mobgen.halo.android.app.ui.MobgenHaloActivity; import com.mobgen.halo.android.app.utils.QReader; /** * Scan qr activity */ public class QRScanActivity extends MobgenHaloActivity implements QReader.QRScanListener { /** * The scan result */ public static final String BUNDLE_SCAN_RESULT = "bundle_scan_result"; /** * The surface view to show the camera */ private SurfaceView mSurfaceView; /** * The qr reader. */ private QReader mQReader; /** * Starts the activity. * * @param activity The activity to start this activity for result */ public static void startActivityForResult(@NonNull Activity activity, int resultCode) { Intent intent = new Intent(activity, QRScanActivity.class); activity.startActivityForResult(intent,resultCode); } @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan_qr); getSupportActionBar().hide(); Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); mSurfaceView = (SurfaceView) findViewById(R.id.camera_view); BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(getApplicationContext()) .setBarcodeFormats(Barcode.QR_CODE) .build(); mQReader = new QReader.Builder(this, mSurfaceView, this) .withBarcodeDetector(barcodeDetector) .withAutoFocus(true) .withCamera(QReader.BACK_CAMERA) .withAutoFocus(true) .withHeight(size.y) .withWidth(size.x) .build(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); } @Override protected void onResume() { super.onResume(); mQReader.startDetector(mSurfaceView); } @Override protected void onPause() { super.onPause(); mQReader.stopDetector(); } @Override public boolean hasBackNavigationToolbar() { return true; } @Override public void onDetected(String scanResult) { Bundle data = new Bundle(); data.putString(BUNDLE_SCAN_RESULT, scanResult); Intent intent = new Intent(); intent.putExtras(data); setResult(RESULT_OK,intent); finish(); } @Override public void onScanError(String errorMsg) { Bundle data = new Bundle(); data.putString(BUNDLE_SCAN_RESULT, errorMsg); Intent intent = new Intent(); intent.putExtras(data); setResult(RESULT_CANCELED,intent); finish(); } }
28.942149
94
0.666191
5bd286ee86123fdebe6827d5744b5b930b3f8677
1,878
package com.jcg.selenium; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeOptions; public class GoogleSearchTest extends TestBase { public GoogleSearchTest(MutableCapabilities capabilities) { super(capabilities); } // public GoogleSearchTest(){ // super(new ChromeOptions()); // } @Test public void openGoogle() { WebDriver webDriver = getDriver(); webDriver.navigate().to("http://www.google.com"); Assert.assertEquals("Google", webDriver.getTitle()); } @Test public void enterGoogleSearchAndViewResults() { WebDriver webDriver = getDriver(); By searchLocator = By.cssSelector("input[value='Google Search']"); webDriver.navigate().to("http://www.google.com"); WebElement searchText = webDriver.findElement(By.cssSelector("input[title=Search]")); searchText.sendKeys("hi"); WebElement searchButton = webDriver.findElement(searchLocator); searchButton.click(); Assert.assertEquals("hi - Google Search", webDriver.getTitle()); } @Test public void enterGoogleSearchAndImageSearch() { WebDriver webDriver = getDriver(); By searchLocator = By.cssSelector("input[value='Google Search']"); webDriver.navigate().to("http://www.google.com"); WebElement searchText = webDriver.findElement(By.cssSelector("input[title=Search]")); searchText.sendKeys("hi"); WebElement searchButton = webDriver.findElement(searchLocator); searchButton.click(); WebElement imageSearch = webDriver.findElement(By.xpath("//a[contains(text(), 'Images')]")); imageSearch.click(); } }
34.145455
100
0.683174
2d57c5b2ae9b7c9ce9fbb39d656dc907f7184b31
1,254
package com.bx.erp.selenium.Promotion; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.is; import org.openqa.selenium.By; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.bx.erp.selenium.BaseSeleniumTest; public class Promotion_R2Test extends BaseSeleniumTest { @BeforeClass public void setUp() { super.setUp(); operatorType = EnumOperatorType.EOT_PRESALE.getIndex(); } @Test public void uTR10presalesSearchPromotion() throws InterruptedException { driver.findElement(By.cssSelector(".layui-icon-rmb")).click(); driver.findElement(By.linkText("满减优惠")).click(); Thread.sleep(1000); driver.switchTo().frame(1); vars.put("count", driver.findElement(By.cssSelector("#layui-laypage-3 > .layui-laypage-count")).getText()); driver.findElement(By.cssSelector(".layui-form-label > span")).click(); Thread.sleep(1000); assertThat(driver.findElement(By.cssSelector(".layui-inline li:nth-child(1)")).getText(), is("所有")); driver.findElement(By.cssSelector(".layui-inline li:nth-child(1)")).click(); Thread.sleep(1000); assertThat(driver.findElement(By.cssSelector("#layui-laypage-3 > .layui-laypage-count")).getText(), is("vars.get(\"count\").toString()")); } }
36.882353
140
0.745614
0ddff74600f77faa85f46538208d952e3831709d
554
package datas; import java.text.ParseException; import java.time.LocalDate; import java.time.Month; import java.time.Period; public class ExercicioUm { public static void main(String[] args) throws ParseException { LocalDate a = LocalDate.now(); LocalDate b = LocalDate.of(a.getYear(), Month.of(9), 06); Period periodo = null; if (a.isAfter(b)) { b = LocalDate.of(a.getYear() + 1, b.getMonth(), b.getDayOfMonth()); periodo = Period.between(a, b); } else { periodo = Period.between(b, a); } System.out.println(periodo); } }
21.307692
70
0.68231
49bdd454d8b1192ef9aaf0c4c70a18e26e093553
6,426
// The MIT License // // Copyright (c) 2004 Evren Sirin // // 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.mindswap.utils; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.net.URL; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.mindswap.owl.vocabulary.RDF; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; public class Utils { public static boolean DEBUG = false; public static Object getHashtableKey(Hashtable h, Object value) { Iterator e = h.entrySet().iterator(); while(e.hasNext()) { Map.Entry entry = (Map.Entry) e.next(); if(entry.getValue().equals(value)) return entry.getKey(); } return null; } public static void printTime(String msg) { System.out.println("Time: (" + System.currentTimeMillis() + ") " + msg); } public static String toString(Object[] array) { String s = "[Array "; if(array != null && array.length > 0) { s += array[0]; for(int i = 1; i < array.length; i++) s += "," + array[i]; } s += "]"; return s; } public static Node getAsNode(String in) { try { org.apache.xerces.parsers.DOMParser parser = new org.apache.xerces.parsers.DOMParser(); parser.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) { if(DEBUG) System.err.println(exception); } public void error(SAXParseException exception) { if(DEBUG) System.err.println(exception); } public void fatalError(SAXParseException exception) { if(DEBUG) System.err.println(exception); } }); parser.parse(new org.xml.sax.InputSource( new StringReader(in))); return parser.getDocument().getDocumentElement(); } catch(Exception e) { //System.out.println("Invalid XML " + in + " " + e); //e.printStackTrace(); } return null; } public static boolean getBoolean(String str) { return (str == null) ? false : str.toLowerCase().equals("true") || str.equals("1"); } public static String toString(boolean b) { return b ? "true" : "false"; } public static String readURL(URL fileURL) throws IOException { return readAll(new InputStreamReader(fileURL.openStream())); } public static String readFile(String fileName) throws FileNotFoundException, IOException { return readAll(new FileReader(fileName)); } public static String readAll(Reader reader) throws IOException { StringBuffer buffer = new StringBuffer(); BufferedReader in = new BufferedReader(reader); int ch; while ((ch = in.read()) > -1) { buffer.append((char)ch); } in.close(); return buffer.toString(); } public static String formatXML( Node node ) { try { StringWriter out = new StringWriter(); Document doc = node.getOwnerDocument(); OutputFormat format = new OutputFormat( doc ); format.setIndenting( true ); format.setLineWidth( 0 ); format.setPreserveSpace( false ); format.setOmitXMLDeclaration( false ); XMLSerializer serial = new XMLSerializer( out, format ); serial.asDOMSerializer(); serial.serialize( doc ); return out.toString(); } catch( IOException e ) { System.err.println( "Problem serializing node " + e ); return "Problem serializing node " + e; } } public static String formatRDF(String rdf) { Node node = getAsNode(rdf); if(node == null) return rdf; else return formatNode(node, " ").substring(System.getProperty("line.separator").length()); } public static String formatNode(Node node, String indent) { String str = ""; int type = node.getNodeType(); if(type == Node.TEXT_NODE) { str = node.getNodeValue().trim(); } else if(type == Node.ELEMENT_NODE) { if(!(node.getParentNode() instanceof org.w3c.dom.Document)) str = System.getProperty("line.separator") + indent + node.getLocalName() + ": "; NodeList children = node.getChildNodes(); int len = (children != null) ? children.getLength() : 0; for (int i = 0; i < len; i++) { str += formatNode(children.item(i), indent + " "); } if(len == 0) { Node rdfResource = node.getAttributes().getNamedItemNS(RDF.getURI().toString(), "resource"); if(rdfResource instanceof Attr) str += URIUtils.getLocalName(((Attr)rdfResource).getValue()); } } return str; } }
31.346341
106
0.620915
bc9a54888b3579b16f5655dbeaf18589efb43def
2,001
package com.chandrakanth.financesystem.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; import org.apache.commons.lang3.builder.ToStringBuilder; /** * This entity is the embeddable table having User Credentials */ @Embeddable public class UserCredentialsIdPK implements Serializable { private static final long serialVersionUID = 1L; @Column(name = "USER_NAME", insertable = true, updatable = false, unique = true) private String userName; @Column(name = "MOBILE_NUMBER", insertable = true, updatable = true, unique = true) private String mobileNumber; public UserCredentialsIdPK() { super(); } public UserCredentialsIdPK(String userName, String mobileNumber) { super(); this.userName = userName; this.mobileNumber = mobileNumber; } public String getMobileNumber() { return mobileNumber; } public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((mobileNumber == null) ? 0 : mobileNumber.hashCode()); result = prime * result + ((userName == null) ? 0 : userName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UserCredentialsIdPK other = (UserCredentialsIdPK) obj; if (mobileNumber == null) { if (other.mobileNumber != null) return false; } else if (!mobileNumber.equals(other.mobileNumber)) return false; if (userName == null) { if (other.userName != null) return false; } else if (!userName.equals(other.userName)) return false; return true; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
23
84
0.712644
4ab6d2b366ef74f61b512e69465a52b6caf38db4
241
package com.charles445.rltweaker.hook; import java.util.concurrent.ConcurrentLinkedDeque; public class HookMinecraft { public static <E> ConcurrentLinkedDeque<E> newConcurrentLinkedDeque() { return new ConcurrentLinkedDeque<E>(); } }
20.083333
70
0.79668
dfa66327973eab6efa5ad667aef7a6dc7650820b
4,550
/* * 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.management.internal.rest; import static org.apache.geode.test.junit.assertions.ClusterManagementListResultAssert.assertManagementListResult; import static org.apache.geode.test.junit.assertions.ClusterManagementRealizationResultAssert.assertManagementResult; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.RestTemplate; import org.springframework.web.context.WebApplicationContext; import org.apache.geode.management.api.ClusterManagementService; import org.apache.geode.management.api.EntityInfo; import org.apache.geode.management.api.RestTemplateClusterManagementServiceTransport; import org.apache.geode.management.cluster.client.ClusterManagementServiceBuilder; import org.apache.geode.management.configuration.Deployment; import org.apache.geode.management.runtime.DeploymentInfo; import org.apache.geode.test.compiler.JarBuilder; import org.apache.geode.test.junit.assertions.ClusterManagementListResultAssert; import org.apache.geode.util.internal.GeodeJsonMapper; @RunWith(SpringRunner.class) @ContextConfiguration(locations = {"classpath*:WEB-INF/management-servlet.xml"}, loader = PlainLocatorContextLoader.class) @WebAppConfiguration @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class DeployManagementIntegrationTest { @Autowired private WebApplicationContext webApplicationContext; // needs to be used together with any BaseLocatorContextLoader private LocatorWebContext context; private ClusterManagementService client; private Deployment deployment; private static final ObjectMapper mapper = GeodeJsonMapper.getMapper(); private File jar1, jar2; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Before public void before() throws IOException { context = new LocatorWebContext(webApplicationContext); client = new ClusterManagementServiceBuilder().setTransport( new RestTemplateClusterManagementServiceTransport( new RestTemplate(context.getRequestFactory()))) .build(); deployment = new Deployment(); jar1 = new File(temporaryFolder.getRoot(), "jar1.jar"); jar2 = new File(temporaryFolder.getRoot(), "jar2.jar"); JarBuilder jarBuilder = new JarBuilder(); jarBuilder.buildJarFromClassNames(jar1, "ClassOne"); jarBuilder.buildJarFromClassNames(jar2, "ClassTwo"); } @Test @WithMockUser public void sanityCheck() { deployment.setFile(jar1); deployment.setGroup("group1"); assertManagementResult(client.create(deployment)).isSuccessful(); deployment.setGroup("group2"); assertManagementResult(client.create(deployment)).isSuccessful(); deployment.setFile(jar2); deployment.setGroup("group2"); assertManagementResult(client.create(deployment)).isSuccessful(); ClusterManagementListResultAssert<Deployment, DeploymentInfo> deploymentResultAssert = assertManagementListResult(client.list(new Deployment())); deploymentResultAssert.isSuccessful() .hasEntityInfo() .hasSize(2) .extracting(EntityInfo::getId) .containsExactlyInAnyOrder("jar1.jar", "jar2.jar"); } }
40.265487
117
0.795165
c2dee87fb56fe7db02f7d53ad8e161ba00a2898e
2,605
package com.ongsat.blog.web.service; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.ongsat.blog.api.entity.vo.admin.blogroll.BlogrollSearchParamVO; import com.ongsat.blog.api.response.Response; import com.ongsat.blog.api.response.ResultBuilder; import com.ongsat.blog.api.response.RspCode; import com.ongsat.blog.api.entity.po.BlogrollPO; import com.ongsat.blog.api.entity.vo.admin.blogroll.BlogrollCreateParamVO; import com.ongsat.blog.api.entity.vo.admin.blogroll.BlogrollDeleteParamVO; import com.ongsat.blog.api.entity.vo.admin.blogroll.BlogrollUpdateParamVO; import com.ongsat.blog.web.common.convert.ConvertObject; import com.ongsat.blog.web.mapper.BlogrollMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class BlogrollService extends ServiceImpl<BlogrollMapper, BlogrollPO> { @Autowired private ConvertObject convertObject; public Response search(BlogrollSearchParamVO blogrollSearchParamVO) { Integer limit = blogrollSearchParamVO.getLimit(); Integer offset = blogrollSearchParamVO.getOffset(); Page<Object> page = new Page<>(offset, limit); List<BlogrollPO> blogrollPOList = super.baseMapper.selectListByPage(page); Map<String, Object> build = new ResultBuilder() .setList(blogrollPOList) .setTotal(page.getTotal()) .build(); return Response.build(RspCode.QUERY_SUCCESS, build); } public Response create(BlogrollCreateParamVO blogrollCreateParamVO) { BlogrollPO blogrollPO = convertObject.toBlogrollPO(blogrollCreateParamVO); int insert = super.baseMapper.insert(blogrollPO); if (insert == 0) { return Response.error(); } return Response.success(); } public Response update(BlogrollUpdateParamVO blogrollUpdateParamVO) { BlogrollPO blogrollPO = convertObject.toBlogrollPO(blogrollUpdateParamVO); int update = super.baseMapper.updateById(blogrollPO); if (update == 0) { return Response.error(); } return Response.success(); } public Response delete(BlogrollDeleteParamVO blogrollDeleteParamVO) { String id = blogrollDeleteParamVO.getId(); int delete = super.baseMapper.deleteById(id); if (delete == 0) { return Response.error(); } return Response.success(); } }
36.690141
82
0.723608
2b72c2b1cb7a80aac96b2fc656045509c974d66b
478
import ognl.MemberAccess; import java.lang.reflect.Member; import java.util.Map; public class DefaultMemberAccess implements MemberAccess { @Override public Object setup(Map map, Object o, Member member, String s) { return null; } @Override public void restore(Map map, Object o, Member member, String s, Object o1) { } @Override public boolean isAccessible(Map map, Object o, Member member, String s) { return true; } }
21.727273
80
0.679916
45d5c2817fa950fffdf09e49287b3f749f0acccf
482
package de.unistuttgart.iste.rss.oo.hamstersimulator.internal.model.territory.command.specification; import de.unistuttgart.iste.rss.oo.hamstersimulator.datatypes.Location; abstract class AbstractTerritoryTileCommandSpecification { protected final Location location; public AbstractTerritoryTileCommandSpecification(final Location location) { super(); this.location = location; } public Location getLocation() { return location; } }
26.777778
100
0.759336
2f910e6f7f189ddd9df79c8ffa1697df83616b42
1,854
package M10Robot.util; import M10Robot.cardModifiers.OverclockModifier; import M10Robot.cards.interfaces.CannotOverclock; import basemod.helpers.CardModifierManager; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.evacipated.cardcrawl.modthespire.lib.SpirePatch; import com.evacipated.cardcrawl.modthespire.lib.SpirePostfixPatch; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.helpers.FontHelper; public class OverclockUtil { public static boolean hasOverclock(AbstractCard c) { return !CardModifierManager.getModifiers(c, OverclockModifier.ID).isEmpty(); } public static int getOverClockPercent(AbstractCard c) { return ((OverclockModifier) CardModifierManager.getModifiers(c, OverclockModifier.ID).get(0)).getRawPercent(); } public static boolean canOverclock(AbstractCard c) { return !(c instanceof CannotOverclock) && c.type != AbstractCard.CardType.STATUS && c.type != AbstractCard.CardType.CURSE; } @SpirePatch(clz = AbstractCard.class, method = "renderTitle") public static class renderOverclockPercent { @SpirePostfixPatch public static void renderPlz(AbstractCard __instance, SpriteBatch sb, Color ___renderColor) { if (AbstractDungeon.player != null && hasOverclock(__instance)) { Color color = Settings.GREEN_TEXT_COLOR.cpy(); color.a = ___renderColor.a; FontHelper.renderRotatedText(sb, FontHelper.cardTitleFont, "+"+getOverClockPercent(__instance)+"%", __instance.current_x, __instance.current_y, 0.0F, 195.0F * __instance.drawScale * Settings.scale, __instance.angle, false, color); } } } }
45.219512
246
0.747033
87bfe15b45d8391aa2b86bf6b34f8501ccde2976
425
package com.citytechinc.cq.component.touchuidialog.widget.autocomplete.values; import com.citytechinc.cq.component.touchuidialog.AbstractTouchUIDialogElement; import com.citytechinc.cq.component.touchuidialog.TouchUIDialogElementParameters; public class AutoCompleteValues extends AbstractTouchUIDialogElement { public AutoCompleteValues(TouchUIDialogElementParameters parameters) { super(parameters); } }
35.416667
81
0.842353
99bdc291e4235a980a4dd4026e8e5f88cd92b923
5,089
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.ballerinalang.services.dispatchers.http; /** * Constants for HTTP. * * @since 0.8.0 */ public class Constants { public static final String BASE_PATH = "BASE_PATH"; public static final String SUB_PATH = "SUB_PATH"; public static final String QUERY_STR = "QUERY_STR"; public static final String RAW_QUERY_STR = "RAW_QUERY_STR"; public static final String DEFAULT_INTERFACE = "default"; public static final String DEFAULT_BASE_PATH = "/"; public static final String DEFAULT_SUB_PATH = "/*"; public static final String PROTOCOL_HTTP = "http"; public static final String PROTOCOL_PACKAGE_HTTP = "ballerina.net.http"; public static final String PROTOCOL_HTTPS = "https"; public static final String HTTP_METHOD = "HTTP_METHOD"; public static final String HTTP_STATUS_CODE = "HTTP_STATUS_CODE"; public static final String HTTP_REASON_PHRASE = "HTTP_REASON_PHRASE"; public static final String HTTP_CONTENT_LENGTH = "Content-Length"; public static final String USER_AGENT_HEADER = "User-Agent"; public static final String PROTOCOL = "PROTOCOL"; public static final String HOST = "HOST"; public static final String PORT = "PORT"; public static final String TO = "TO"; public static final String HTTP_PACKAGE_PATH = "ballerina.net.http"; public static final String WS_PACKAGE_PATH = "ballerina.net.ws"; public static final String HTTP_METHOD_GET = "GET"; public static final String HTTP_METHOD_POST = "POST"; public static final String HTTP_METHOD_PUT = "PUT"; public static final String HTTP_METHOD_PATCH = "PATCH"; public static final String HTTP_METHOD_DELETE = "DELETE"; public static final String HTTP_METHOD_OPTIONS = "OPTIONS"; public static final String HTTP_METHOD_HEAD = "HEAD"; /* Annotations */ public static final String ANNOTATION_NAME_PATH = "Path"; public static final String ANNOTATION_NAME_CONFIG = "config"; public static final String ANNOTATION_ATTRIBUTE_HOST = "host"; public static final String ANNOTATION_ATTRIBUTE_PORT = "port"; public static final String ANNOTATION_ATTRIBUTE_BASE_PATH = "basePath"; public static final String ANNOTATION_ATTRIBUTE_SCHEME = "scheme"; public static final String ANNOTATION_ATTRIBUTE_KEY_STORE_FILE = "keyStoreFile"; public static final String ANNOTATION_ATTRIBUTE_KEY_STORE_PASS = "keyStorePass"; public static final String ANNOTATION_ATTRIBUTE_CERT_PASS = "certPass"; public static final String ANNOTATION_ATTRIBUTE_VERSION = "version"; public static final String ANNOTATION_METHOD_GET = HTTP_METHOD_GET; public static final String ANNOTATION_METHOD_POST = HTTP_METHOD_POST; public static final String ANNOTATION_METHOD_PUT = HTTP_METHOD_PUT; public static final String ANNOTATION_METHOD_PATCH = HTTP_METHOD_PATCH; public static final String ANNOTATION_METHOD_DELETE = HTTP_METHOD_DELETE; public static final String ANNOTATION_METHOD_OPTIONS = HTTP_METHOD_OPTIONS; /* WebSocket Annotations */ public static final String PROTOCOL_WEBSOCKET = "ws"; public static final String PROTOCOL_PACKAGE_WEBSOCKET = "ballerina.net.ws"; public static final String ANNOTATION_NAME_WEBSOCKET_UPGRADE_PATH = "WebSocketUpgradePath"; public static final String ANNOTATION_NAME_ON_OPEN = "OnOpen"; public static final String ANNOTATION_NAME_ON_TEXT_MESSAGE = "OnTextMessage"; public static final String ANNOTATION_NAME_ON_BINARY_MESSAGE = "OnBinaryMessage"; public static final String ANNOTATION_NAME_ON_PONG_MESSAGE = "OnPongMessage"; public static final String ANNOTATION_NAME_ON_CLOSE = "OnClose"; public static final String ANNOTATION_NAME_ON_ERROR = "OnError"; public static final String CONNECTION = "Connection"; public static final String UPGRADE = "Upgrade"; public static final String WEBSOCKET_UPGRADE = "websocket"; public static final String CHANNEL_ID = "CHANNEL_ID"; public static final String WEBSOCKET_SESSION = "WEBSOCKET_SESSION"; public static final String ANNOTATION_SOURCE_KEY_INTERFACE = "interface"; public static final String VALUE_ATTRIBUTE = "value"; public static final String COOKIE_HEADER = "Cookie"; public static final String SESSION_ID = "BSESSIONID="; public static final String PATH = "Path="; public static final String RESPONSE_COOKIE_HEADER = "Set-Cookie"; }
48.932692
95
0.759285
304cbc91e410c7b08308378b12e36464fbd80e92
21,797
package cn.com.king.web.action.log; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanNameAware; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import cn.com.king.dto.DBDto; import cn.com.taiji.tools.RTools; import cn.com.taiji.web.service.BaseService2; /** * * 类名称:DataSourceImpl.java 类描述: 数据源管理 创建人:zhongdd 创建时间:2016年10月28日 上午9:50:21 * * @version */ public class DataSourceImpl implements ApplicationContextAware, BeanNameAware { private String beanName; private ApplicationContext applicationContext; public String getBeanName() { return beanName; } @Override public void setBeanName(String beanName) { this.beanName = beanName; } public ApplicationContext getApplicationContext() { if (applicationContext == null) { applicationContext = new FileSystemXmlApplicationContext( this.getClass().getResource("/") + "spring/app-datasouce-config.xml"); } return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public DataSource getDriverManagerDataSource(DBDto dbDto) { if ("sgongsj".equals(dbDto.getDbid())) { DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName(dbDto.getDbdriver()); ds.setUsername(dbDto.getUsername()); ds.setPassword(dbDto.getPassword()); ds.setDriverClassName("com.sybase.jdbc3.jdbc.SybDriver"); ds.setUrl("jdbc:sybase:Tds:" + dbDto.getDblink() + "/" + dbDto.getDbname() + "?charset=cp936"); //System.out.println("DBinfo:" + dbDto.getDbid() + "--" + dbDto.getDbname() + "--" + dbDto.getDbtype() + "--" // + dbDto.getDbdriver() + "--" + dbDto.getDblink()); return ds; } else { DataSource dataSource = (DataSource) this.getApplicationContext().getBean(dbDto.getDbid()); return dataSource; } } public DataSource getDriverManagerDataSource(String dbid) { DataSource dataSource = (DataSource) this.getApplicationContext().getBean(dbid); return dataSource; } /** * * 功能名称:分页查询 * 参数: 表名、查询条件 * 返回值:int * 作者: zhongdd * 创建时间: 2017年3月10日 下午4:49:07 * 说明: * table_name 表名 * filter 查询条件 * filter.put("id:=","AAAA") ---> id='AAAA' * filter.put("name","BBBB") ---> name like '%BBBB%' * sort 排序字段 * filter.put("index_num","asc") ---> order by index_num asc * filter.put("index_num","desc") ---> order by index_num desc * selectCloum 指定要查询的字段 例如 id,name,cretae_time * currentPage 当前第几页 * pageSize 每页多少条 * * */ public List<Map<String, Object>> selectPageListByTable(String table_name, Map<String, String> filter, Map<String, String> sort, int currentPage, int pageSize, String selectCloum) throws Exception { DataSource datasource = getDriverManagerDataSource("dataSource");// edas数据库 JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); String sql = fillSelectSqlForTable(table_name, filter, sort, currentPage, pageSize, selectCloum, 0); List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); return list; } public List<Map<String, Object>> selectPageListBySql(String sqlview, Map<String, String> filter, Map<String, String> sort, int currentPage, int pageSize, String selectCloum) throws Exception { DataSource datasource = getDriverManagerDataSource("dataSource");// edas数据库 JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); String sql = fillSelectSqlForSqlView(sqlview, filter, sort, currentPage, pageSize, selectCloum, 0); List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); return list; } /** * * 功能名称:求总数 * 参数: 表名、查询条件 * 返回值:int * 作者: zhongdd * 创建时间: 2017年3月10日 下午4:49:07 * 说明: * table_name 表名 * filter 查询条件 * filter.put("id:=","AAAA") ---> id='AAAA' * filter.put("name","BBBB") ---> name like '%BBBB%' * */ public int selectCountForTable(String table_name, Map<String, String> filter) throws Exception { DataSource datasource = getDriverManagerDataSource("dataSource");// edas数据库 JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); String sql = fillSelectSqlForTable(table_name, filter, null, 0, 0, null, 1); int rtn = jdbcTemplate.queryForObject(sql, int.class); return rtn; } public int selectCountForSqlView(String SqlView, Map<String, String> filter) throws Exception { DataSource datasource = getDriverManagerDataSource("dataSource");// edas数据库 JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); String sql = fillSelectSqlForSqlView(SqlView, filter, null, 0, 0, null, 1); int rtn = jdbcTemplate.queryForObject(sql, int.class); return rtn; } public int selectCountForSqlView1(String SqlView, Map<String, String> filter) throws Exception { DataSource datasource = getDriverManagerDataSource("dataSource");// edas数据库 JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); String sql = fillSelectSqlForSqlView1(SqlView, filter, null, 0, 0, null, 1); int rtn = jdbcTemplate.queryForObject(sql, int.class); return rtn; } /** * * 功能名称:sql 拼接 * 参数: 表名、查询条件 * 返回值:int * 作者: zhongdd * 创建时间: 2017年3月10日 下午4:49:07 * 说明: * table_name 表名 * filter 查询条件 * filter.put("id:=","AAAA") ---> id='AAAA' * filter.put("name","BBBB") ---> name like '%BBBB%' * sort 排序字段 * filter.put("index_num","asc") ---> order by index_num asc * filter.put("index_num","desc") ---> order by index_num desc * selectCloum 指定要查询的字段 例如 id,name,cretae_time * currentPage 当前第几页 * pageSize 每页多少条 * sqlType 拼接sql类型 0:查询 、 1: 求总数(count) * */ public String fillSelectSqlForTable(String table_name, Map<String, String> filter, Map<String, String> sort, int currentPage, int pageSize, String selectCloum, int sqlType) { String sql = ""; if (sqlType == 1) { sql = "select count(1) from " + table_name; } else { if (!RTools.string.isEmpty(selectCloum)) { sql = "select " + selectCloum + " from " + table_name; } else { sql = "select * from " + table_name; } } String key = null; String value = null; if (filter != null && !filter.isEmpty()) { // Map<String, String> map = new HashMap<String, String>(); int index = 0; for (Map.Entry<String, String> entry : filter.entrySet()) { key = entry.getKey(); value = entry.getValue(); if (key.contains(":")) { String[] ks = key.split(":"); if (index == 0) { sql += " where " + ks[0] + "= '" + value+"' "; } else { sql += " and " + ks[0] + "= '" + value+"' "; } } else { if (index == 0) { sql += " where " + key + "like '%" + value + "%' "; } else { sql += " and " + key + "like '%" + value + "%' "; } } index++; } } if (sqlType != 1) { if (sort != null && !sort.isEmpty() && sort.size() == 1) { for (Map.Entry<String, String> entry : sort.entrySet()) { key = entry.getKey(); value = entry.getValue(); sql += " order by " + key + " " + value; } } sql += " LIMIT " + (currentPage - 1) * pageSize + "," + pageSize + ""; } return sql; } /** * * 功能名称:sql 拼接 * 参数: 查询sql * 返回值:int * 作者: zhongdd * 创建时间: 2017年3月10日 下午4:49:07 * 说明: * table_name 表名 * filter 查询条件 * filter.put("id:=","AAAA") ---> id='AAAA' * filter.put("name","BBBB") ---> name like '%BBBB%' * sort 排序字段 * filter.put("index_num","asc") ---> order by index_num asc * filter.put("index_num","desc") ---> order by index_num desc * selectCloum 指定要查询的字段 例如 id,name,cretae_time * currentPage 当前第几页 * pageSize 每页多少条 * sqlType 拼接sql类型 0:查询 、 1: 求总数(count) * */ public String fillSelectSqlForSqlView(String sql, Map<String, String> filter, Map<String, String> sort, int currentPage, int pageSize, String selectCloum, int sqlType) { String key = null; String value = null; if (filter != null && !filter.isEmpty()) { // Map<String, String> map = new HashMap<String, String>(); int index = 0; for (Map.Entry<String, String> entry : filter.entrySet()) { key = entry.getKey(); value = entry.getValue(); if(key.contains("<")){ String[] ks = key.split("<"); if (index == 0) { sql += " where " + ks[0] + " < " + value; } else { sql += " and " + ks[0] + " < " + value; } }else{ if(value == null){ if (key.contains(":")) { String[] ks = key.split(":"); if (index == 0) { sql += " where " + ks[0] + " is " + value+" "; } else { sql += " and " + ks[0] + " is " + value+" "; } } }else{ if (key.contains(":")) { String[] ks = key.split(":"); if (index == 0) { sql += " where " + ks[0] + "= '" + value+"' "; } else { sql += " and " + ks[0] + "= '" + value+"' "; } } else { if (index == 0) { if(key.contains("xxl_utime")){ sql+=" where " + value; }else{ sql += " where " + key + " like '%" + value + "%' "; } } else { if(key.contains("xxl_utime")){ sql+=" and "+ value; }else{ sql += " and " + key + " like '%" + value + "%' "; } } } } } index++; } } if (sqlType != 1) { if (sort != null && !sort.isEmpty() && sort.size() == 1) { for (Map.Entry<String, String> entry : sort.entrySet()) { key = entry.getKey(); value = entry.getValue(); sql += " order by " + key + " " + value; } } sql += " LIMIT " + (currentPage - 1) * pageSize + "," + pageSize + ""; } return sql; } public String fillSelectSqlForSqlView1(String sql, Map<String, String> filter, Map<String, String> sort, int currentPage, int pageSize, String selectCloum, int sqlType) { String key = null; String value = null; if (filter != null && !filter.isEmpty()) { for (Map.Entry<String, String> entry : filter.entrySet()) { key = entry.getKey(); value = entry.getValue(); if(key.contains("=in")){ String[] ks = key.split("=in"); sql += " and " + ks[0] + " in " + value; }else{ if(key.contains("<")){ String[] ks = key.split("<"); sql += " and " + ks[0] + " < " + value; }else{ if(value == null){ if (key.contains(":")) { String[] ks = key.split(":"); sql += " and " + ks[0] + " is " + value+" "; } }else{ if (key.contains(":")) { String[] ks = key.split(":"); sql += " and " + ks[0] + "= '" + value+"' "; } else { if(key.contains("xxl_utime")){ sql+=" and "+ value; }else{ sql += " and " + key + " like '%" + value + "%' "; } } } } } } } if (sqlType != 1) { if (sort != null && !sort.isEmpty() && sort.size() == 1) { for (Map.Entry<String, String> entry : sort.entrySet()) { key = entry.getKey(); value = entry.getValue(); sql += " order by " + key + " " + value; } } sql += " LIMIT " + (currentPage - 1) * pageSize + "," + pageSize + ""; } return sql; } /** * * 功能名称:sql 拼接 * 参数: 查询sql * 返回值:int * 作者: zhongdd * 创建时间: 2017年3月10日 下午4:49:07 * 说明: * table_name 表名 * filter 查询条件 * filter.put("id:=","AAAA") ---> id='AAAA' * filter.put("name","BBBB") ---> name like '%BBBB%' * sort 排序字段 * filter.put("index_num","asc") ---> order by index_num asc * filter.put("index_num","desc") ---> order by index_num desc * selectCloum 指定要查询的字段 例如 id,name,cretae_time * currentPage 当前第几页 * pageSize 每页多少条 * sqlType 拼接sql类型 0:查询 、 1: 求总数(count) * */ public String fillSelectSqlForSqlViewAddGroup(String sql, Map<String, String> filter, Map<String, String> sort, String group, int currentPage, int pageSize, String selectCloum, int sqlType) { String key = null; String value = null; if (filter != null && !filter.isEmpty()) { // Map<String, String> map = new HashMap<String, String>(); int index = 0; for (Map.Entry<String, String> entry : filter.entrySet()) { key = entry.getKey(); value = entry.getValue(); if (key.contains(":")) { String[] ks = key.split(":"); if (index == 0) { sql += " where " + ks[0] + "= '" + value + "' "; } else { sql += " and " + ks[0] + "= '" + value + "' "; } }else if(key.contains(">=")){ String[] ks = key.split(">="); if (index == 0) { sql += " where " + ks[0] + ">= '" + value + "' "; } else { sql += " and " + ks[0] + " >= '" + value + "' "; } }else if(key.contains("<=")){ String[] ks = key.split("<="); if (index == 0) { sql += " where " + ks[0] + "<= '" + value + "' "; } else { sql += " and " + ks[0] + " <= '" + value + "' "; } }else if(key.contains("<>")){ String[] ks = key.split("<>"); if (index == 0) { sql += " where " + ks[0] + "<> '" + value + "' "; } else { sql += " and " + ks[0] + "<> '" + value + "' "; } } else { if (index == 0) { if (key.contains("xxl_utime")) { sql += " where " + value; } else { sql += " where " + key + " like '%" + value + "%' "; } } else { if (key.contains("xxl_utime")) { sql += " and " + value; } else { sql += " and " + key + " like '%" + value + "%' "; } } } index++; } } if (sqlType != 1) { if (group != null && !group.isEmpty()) { sql += " group by " + group; } } if (sqlType != 1) { if (sort != null && !sort.isEmpty() && sort.size() > 0) { sql += " order by " ; for (Map.Entry<String, String> entry : sort.entrySet()) { key = entry.getKey(); value = entry.getValue(); sql += key + " " + value +" ,"; } sql = sql.substring(0, sql.length()-1); } sql += " LIMIT " + (currentPage - 1) * pageSize + "," + pageSize + ""; } return sql; } public String fillSelectSqlForSqlViewAddGroup1(String sql, Map<String, String> filter, Map<String, String> sort, String group, int currentPage, int pageSize, String selectCloum, int sqlType) { String key = null; String value = null; if (filter != null && !filter.isEmpty()) { // Map<String, String> map = new HashMap<String, String>(); int index = 0; for (Map.Entry<String, String> entry : filter.entrySet()) { key = entry.getKey(); value = entry.getValue(); if (key.contains(":")) { String[] ks = key.split(":"); if (index == 0) { sql += " where " + ks[0] + "= '" + value + "' "; } else { sql += " and " + ks[0] + "= '" + value + "' "; } }else if(key.contains(">=")){ String[] ks = key.split(">="); if (index == 0) { sql += " where " + ks[0] + ">= '" + value + "' "; } else { sql += " and " + ks[0] + " >= '" + value + "' "; } }else if(key.contains("<=")){ String[] ks = key.split("<="); if (index == 0) { sql += " where " + ks[0] + "<= '" + value + "' "; } else { sql += " and " + ks[0] + " <= '" + value + "' "; } }else if(key.contains("=in")){ String[] ks = key.split("=in"); if (index == 0) { sql += " where " + ks[0] + " in (" + value + ") "; } else { sql += " and " + ks[0] + " in (" + value + ") "; } }else if(key.contains("<>")){ String[] ks = key.split("<>"); if (index == 0) { sql += " where " + ks[0] + "<> '" + value + "' "; } else { sql += " and " + ks[0] + "<> '" + value + "' "; } } else if(key.contains("is")){ String[] ks = key.split("is"); if (index == 0) { sql += " where " + ks[0] + " is null)"; } else { sql += " and " + ks[0] + " is null)"; } }else { if(index == 0){ sql += " where " + key + " like '%" + value + "%' "; }else{ sql += " and " + key + " like '%" + value + "%' "; } } index++; } } if (sqlType != 1) { if (group != null && !group.isEmpty()) { sql += " group by " + group; } } if (sqlType != 1) { if (sort != null && !sort.isEmpty() && sort.size() > 0) { sql += " order by " ; for (Map.Entry<String, String> entry : sort.entrySet()) { key = entry.getKey(); value = entry.getValue(); sql += key + " " + value +" ,"; } sql = sql.substring(0, sql.length()-1); } sql += " LIMIT " + (currentPage - 1) * pageSize + "," + pageSize + ""; } return sql; } /**oracle---- * @param sql * @param filter * @param sort * @param group * @param currentPage * @param pageSize * @param selectCloum * @param sqlType * @return */ public String fillOracleSelectForSqlViewAddGroup(String sql, Map<String, String> filter, Map<String, String> sort, String group, int currentPage, int pageSize, String selectCloum, int sqlType) { String key = null; String value = null; if (filter != null && !filter.isEmpty()) { // Map<String, String> map = new HashMap<String, String>(); int index = 0; for (Map.Entry<String, String> entry : filter.entrySet()) { key = entry.getKey(); value = entry.getValue(); if (key.contains(":")) { String[] ks = key.split(":"); if (index == 0) { sql += " where " + ks[0] + "= '" + value+"' "; } else { sql += " and " + ks[0] + "= '" + value+"' "; } } else { if (index == 0) { sql += " where " + key + "like '%" + value + "%' "; } else { sql += " and " + key + "like '%" + value + "%' "; } } index++; } } if (sqlType != 1) { if (group != null && !group.isEmpty()) { sql += " group by " + group; } } if (sqlType != 1) { if (sort != null && !sort.isEmpty() && sort.size() == 1) { for (Map.Entry<String, String> entry : sort.entrySet()) { key = entry.getKey(); value = entry.getValue(); sql += " order by " + key + " " + value; } } sql = "select * from ( select ROWNUM as rowno ,ta.* from ("+sql+ ") ta) tt where tt.rowno > " + (currentPage - 1) * pageSize + " and tt.rowno <= " + currentPage*pageSize + ""; } return sql; } public String fillOracleSelectForSqlViewAddGroup1(String sql, Map<String, String> filter, Map<String, String> sort, String group, int currentPage, int pageSize, String selectCloum, int sqlType) { String key = null; String value = null; if (filter != null && !filter.isEmpty()) { // Map<String, String> map = new HashMap<String, String>(); int index = 0; for (Map.Entry<String, String> entry : filter.entrySet()) { key = entry.getKey(); value = entry.getValue(); if (key.contains(":")) { String[] ks = key.split(":"); if (index == 0) { sql += " where " + ks[0] + "= '" + value + "' "; } else { sql += " and " + ks[0] + "= '" + value + "' "; } }else if(key.contains(">=")){ String[] ks = key.split(">="); if (index == 0) { sql += " where " + ks[0] + ">= '" + value + "' "; } else { sql += " and " + ks[0] + " >= '" + value + "' "; } }else if(key.contains("<=")){ String[] ks = key.split("<="); if (index == 0) { sql += " where " + ks[0] + "<= '" + value + "' "; } else { sql += " and " + ks[0] + " <= '" + value + "' "; } }else if(key.contains("=in")){ String[] ks = key.split("=in"); if (index == 0) { sql += " where " + ks[0] + " in (" + value + ") "; } else { sql += " and " + ks[0] + " in (" + value + ") "; } }else if(key.contains("<>")){ String[] ks = key.split("<>"); if (index == 0) { sql += " where " + ks[0] + " is not null " + value + " "; } else { sql += " and " + ks[0] + " is not null " + value + " "; } } else if(key.contains("is")){ String[] ks = key.split("is"); if (index == 0) { sql += " where " + ks[0] + " is null"; } else { sql += " and " + ks[0] + " is null"; } }else { if(index == 0){ sql += " where " + key + " like '%" + value + "%' "; }else{ sql += " and " + key + " like '%" + value + "%' "; } } index++; } } if (sqlType != 1) { if (group != null && !group.isEmpty()) { sql += " group by " + group; } } if (sqlType != 1) { if (sort != null && !sort.isEmpty() && sort.size() == 1) { for (Map.Entry<String, String> entry : sort.entrySet()) { key = entry.getKey(); value = entry.getValue(); sql += " order by " + key + " " + value; } } sql = "select * from ( select ROWNUM as rowno ,ta.* from ("+sql+ ") ta) tt where tt.rowno > " + (currentPage - 1) * pageSize + " and tt.rowno <= " + currentPage*pageSize + ""; } return sql; } public int getNextSeq(String string) { return 0; } public void insert(String string, Map<String, Object> log) { } }
31.272597
193
0.52521
85647f3747aab50c586fb68a5b16118d34aaff63
2,467
/** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. jclouds 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.jclouds.savvis.vpdc.xml; import static org.jclouds.util.SaxUtils.currentOrNull; import static org.jclouds.util.SaxUtils.equalsOrSuffix; import java.util.Map; import javax.inject.Inject; import javax.inject.Provider; import org.jclouds.ovf.xml.SectionHandler; import org.jclouds.savvis.vpdc.domain.NetworkConfigSection; import org.jclouds.util.SaxUtils; import org.xml.sax.Attributes; /** * @author Adrian Cole */ public class NetworkConfigSectionHandler extends SectionHandler<NetworkConfigSection, NetworkConfigSection.Builder> { @Inject public NetworkConfigSectionHandler(Provider<NetworkConfigSection.Builder> builderProvider) { super(builderProvider); } public void startElement(String uri, String localName, String qName, Attributes attrs) { Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs); if (equalsOrSuffix(qName, "Section") && "vApp:NetworkConfigSectionType".equals(attributes.get("type"))) { builder.network(attributes.get("Network")); builder.netmask(attributes.get("Netmask")); builder.gateway(attributes.get("Gateway")); } else if (equalsOrSuffix(qName, "NatRule")) { builder.internalToExternalNATRule(attributes.get("internalIP"), attributes.get("externalIP")); } } @Override public void endElement(String uri, String localName, String qName) { if (equalsOrSuffix(qName, "FenceMode")) { builder.fenceMode(currentOrNull(currentText)); } else if (equalsOrSuffix(qName, "Dhcp")) { builder.dhcp(Boolean.valueOf(currentOrNull(currentText))); } super.endElement(uri, localName, qName); } }
37.953846
117
0.736927
db8cb6a6d387b819375b326952ae99985dedf2fc
914
package com.freeter.modules.cart.service.impl; import org.springframework.stereotype.Service; import java.util.Map; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.freeter.common.utils.PageUtils; import com.freeter.common.utils.Query; import com.freeter.modules.cart.dao.CartDao; import com.freeter.modules.cart.entity.CartEntity; import com.freeter.modules.cart.service.CartService; @Service("cartService") public class CartServiceImpl extends ServiceImpl<CartDao, CartEntity> implements CartService { @Override public PageUtils queryPage(Map<String, Object> params) { Page<CartEntity> page = this.selectPage( new Query<CartEntity>(params).getPage(), new EntityWrapper<CartEntity>() ); return new PageUtils(page); } }
31.517241
94
0.754923
3bab80effd768b5ab40c25755a53dba4fb03a0cf
572
package com.fc.v2.course.dao; import com.fc.v2.course.domain.WbCoursekindDO; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Mapper; /** * * @author whw * @email 1992lcg@163.com * @date 2021-06-01 01:02:54 */ @Mapper public interface WbCoursekindDao { WbCoursekindDO get(Integer id); List<WbCoursekindDO> list(Map<String,Object> map); int count(Map<String,Object> map); int save(WbCoursekindDO wbCoursekind); int update(WbCoursekindDO wbCoursekind); int remove(Integer id); int batchRemove(Integer[] ids); }
17.333333
51
0.730769
96d0269dfc64e7a6653d27c79417887af2306b0c
1,374
package steps; import static org.junit.Assert.assertEquals; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import io.cucumber.java.pt.Então; import io.cucumber.java.pt.Quando; import setup.Configuracao; public class CasoDeTesteDoisSteps { WebElement conteudoDesejado; String tituloDesejado; String msgValidation; String textoDesejado; @Quando("clica no item servicos") public void clica_no_item_servicos() { Configuracao.driver.findElement(By.xpath("//*[@id=\"navigation-menu\"]/div[2]/div[1]")).click(); } @Então("deve mostrar os {string}") public void deve_mostrar_os(String nomeEsperado) throws InterruptedException { Thread.sleep(1000); conteudoDesejado = Configuracao.driver.findElement(By.linkText(nomeEsperado)); textoDesejado = conteudoDesejado.getText(); assertEquals(nomeEsperado, textoDesejado); Configuracao.close(); } @Quando("clica no item do menu cloud") public void clica_no_item_do_menu_cloud() { Configuracao.driver.findElement(By.linkText("Cloud")).click(); } @Então("deve encontrar o titulo servicos de cloud") public void deve_encontrar_o_titulo_servicos_de_cloud() throws InterruptedException { Thread.sleep(2000); tituloDesejado = Configuracao.driver.findElement(By.tagName("h1")).getText(); assertEquals("Serviços de Cloud", tituloDesejado); Configuracao.close(); } }
27.48
98
0.766376
b2f004f8299608378a81970d4c85d178437b8ece
268
package cn.glogs.activeauth.iamcore.exception; public class HTTP404Exception extends HTTPException { public HTTP404Exception(Throwable cause) { super(cause.getMessage(), cause); } public HTTP404Exception(String msg) { super(msg); } }
22.333333
53
0.697761
bd3bbc8d9b9469441244ac479bd242436f19511d
7,039
package com.example.suyashl.WhenWeMeetAgain; /** * Created by Ranjan on 24-01-2015. */ import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; public class FriendsDbAdapter { private static final String F_DATABASE_NAME = "data2"; private static final String F_DATABASE_TABLE = "friends"; private static final int F_DATABASE_VERSION = 3; public static final String KEYF_NAME = "name"; public static final String KEYF_BT = "bluetooth"; public static final String KEYF_ROWID = "_id"; private static final String TAG = "FriendsDbAdapter"; private DatabaseHelper mDbHelper2; private SQLiteDatabase mDb2; /** * Database creation SQL statement */ private static final String F_DATABASE_CREATE = "create table " + F_DATABASE_TABLE + " (" + KEYF_ROWID + " integer primary key autoincrement, " + KEYF_NAME + " text not null, " + KEYF_BT + " text not null);"; private final Context mCtx2; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, F_DATABASE_NAME, null, F_DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(F_DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + F_DATABASE_TABLE); onCreate(db); } } /** * Constructor - takes the context to allow the database to be * opened/created * * @param ctx the Context within which to work */ public FriendsDbAdapter(Context ctx) { this.mCtx2 = ctx; } /** * Open the database. If it cannot be opened, try to create a new * instance of the database. If it cannot be created, throw an exception to * signal the failure * * @return this (self reference, allowing this to be chained in an * initialization call) * @throws android.database.SQLException if the database could be neither opened or created */ public FriendsDbAdapter open() throws SQLException { mDbHelper2 = new DatabaseHelper(mCtx2); mDb2 = mDbHelper2.getWritableDatabase(); return this; } public void close() { mDbHelper2.close(); } /** * Create a new reminder using the title, description and reminder date time provided. * If the reminder is successfully created return the new rowId * for that reminder, otherwise return a -1 to indicate failure. * * @param name the description of the reminder * @return rowId or -1 if failed */ public long createFriends(String name, String bluetooth) { ContentValues initialValues = new ContentValues(); initialValues.put(KEYF_NAME, name); initialValues.put(KEYF_BT, bluetooth); return mDb2.insert(F_DATABASE_TABLE, null, initialValues); } /** * Delete the reminder with the given rowId * * @param rowId id of reminder to delete * @return true if deleted, false otherwise */ public boolean deleteFriends(long rowId) { return mDb2.delete(F_DATABASE_TABLE, KEYF_ROWID + "=" + rowId, null) > 0; } /** * Return a Cursor over the list of all reminders in the database * * @return Cursor over all reminders */ public Cursor fetchAllFriends() { return mDb2.query(F_DATABASE_TABLE, new String[] {KEYF_ROWID, KEYF_NAME, KEYF_BT}, null, null, null, null, null); } /** * Return a Cursor positioned at the reminder that matches the given rowId * * @param rowId id of reminder to retrieve * @return Cursor positioned to matching reminder, if found * @throws SQLException if reminder could not be found/retrieved */ public Cursor fetchFriends(long rowId) throws SQLException { Cursor mCursor = mDb2.query(true, F_DATABASE_TABLE, new String[] {KEYF_ROWID, KEYF_NAME, KEYF_BT}, KEYF_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Update the reminder using the details provided. The reminder to be updated is * specified using the rowId, and it is altered to use the title, body and reminder date time * values passed in * * @param rowId id of reminder to update * @param body value to set reminder body to * @return true if the reminder was successfully updated, false otherwise */ public boolean updateFriends(long rowId, String body, String bluetooth) { ContentValues args = new ContentValues(); args.put(KEYF_NAME, body); args.put(KEYF_BT, bluetooth); return mDb2.update(F_DATABASE_TABLE, args, KEYF_ROWID + "=" + rowId, null) > 0; } public List<String> getAllLabels(){ List<String> labels = new ArrayList<String>(); // Select All Query String selectQuery = " SELECT " + KEYF_NAME + " FROM "+ F_DATABASE_TABLE; SQLiteDatabase mDb2ReadableDatabase = mDbHelper2.getReadableDatabase(); Cursor cursor = mDb2ReadableDatabase.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { labels.add(cursor.getString(0)); } while (cursor.moveToNext()); } // closing connection cursor.close(); mDb2ReadableDatabase.close(); // returning labels return labels; } public String SearchTable(String rem) { String bluetooth = ""; String query = "SELECT bluetooth FROM " + F_DATABASE_TABLE + " WHERE " + KEYF_NAME + " = '" + rem + "';"; mDbHelper2 = new DatabaseHelper(mCtx2); mDb2 = mDbHelper2.getReadableDatabase(); Cursor c = mDb2.rawQuery(query, null); if(c != null) { if(c.moveToFirst()) { do { bluetooth = c.getString(c.getColumnIndex(KEYF_BT)); } while (c.moveToNext()); } } c.close(); return bluetooth; } }
31.850679
114
0.603921
bfe7b0249f8cc4ac04315332849a242166ee7f5d
14,104
package uk.gov.pay.api.resources.directdebit; import com.google.common.collect.ImmutableMap; import io.restassured.response.ValidatableResponse; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.apache.commons.lang3.RandomStringUtils; import org.apache.http.HttpStatus; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import uk.gov.pay.api.it.fixtures.PaymentNavigationLinksFixture; import uk.gov.pay.api.it.fixtures.TestDirectDebitPaymentSearchResult; import uk.gov.pay.api.model.DirectDebitPaymentState; import java.util.List; import java.util.Map; import static io.restassured.RestAssured.given; import static io.restassured.http.ContentType.JSON; import static javax.ws.rs.core.HttpHeaders.AUTHORIZATION; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.core.Is.is; import static uk.gov.pay.api.it.fixtures.PaginatedPaymentSearchResultFixture.aPaginatedPaymentSearchResult; import static uk.gov.pay.api.it.fixtures.TestDirectDebitPaymentSearchResult.TestDirectDebitPaymentSearchResultBuilder.aTestDirectDebitPaymentSearchResult; import static uk.gov.pay.api.model.TokenPaymentType.DIRECT_DEBIT; import static uk.gov.pay.api.resources.directdebit.DirectDebitPaymentsResourceGetIT.SearchDirectDebitPaymentsValidationParameters.CreatePaymentRequestValidationParametersBuilder.someParameters; @RunWith(JUnitParamsRunner.class) public class DirectDebitPaymentsResourceGetIT extends DirectDebitResourceITBase { private static final String GET_PATH = "/v1/directdebit/payments"; @Test public void getPayment_ReturnsDirectDebitPayment() { publicAuthMockClient.mapBearerTokenToAccountId(API_KEY, GATEWAY_ACCOUNT_ID, DIRECT_DEBIT); connectorDDMockClient.respondWithChargeFound("mandate2000", 1000, GATEWAY_ACCOUNT_ID, "ch_ab2341da231434l", new DirectDebitPaymentState("created", "payment_state_details"), "http://example.com", "a description", "a reference", "gocardless", "2018-06-11T19:40:56Z", "token_1234567asdf"); given().port(app.getLocalPort()) .accept(JSON) .contentType(JSON) .header(AUTHORIZATION, "Bearer " + API_KEY) .get("/v1/directdebit/payments/ch_ab2341da231434l") .then() .statusCode(200) .contentType(JSON) .body("payment_id", is("ch_ab2341da231434l")) .body("reference", is("a reference")) .body("description", is("a description")) .body("amount", is(1000)) .body("state.status", is("created")) .body("state.details", is("payment_state_details")) .body("payment_provider", is("gocardless")) .body("created_date", is("2018-06-11T19:40:56Z")) .body("_links.self.href", is(paymentLocationFor("ch_ab2341da231434l"))) .body("_links.self.method", is("GET")) .body("_links.mandate.href", is(mandateLocationFor("mandate2000"))) .body("_links.mandate.method", is("GET")); } @Test public void searchPayments_success() { PaymentNavigationLinksFixture links = new PaymentNavigationLinksFixture() .withPrevLink("http://server:port/path?query=prev&from_date=2016-01-01T23:59:59Z") .withNextLink("http://server:port/path?query=next&from_date=2016-01-01T23:59:59Z") .withSelfLink("http://server:port/path?query=self&from_date=2016-01-01T23:59:59Z") .withFirstLink("http://server:port/path?query=first&from_date=2016-01-01T23:59:59Z") .withLastLink("http://server:port/path?query=last&from_date=2016-01-01T23:59:59Z"); List<TestDirectDebitPaymentSearchResult> payments = aTestDirectDebitPaymentSearchResult() .buildMultiple(3); String ddConnectorSearchResult = aPaginatedPaymentSearchResult() .withCount(3) .withPage(2) .withTotal(40) .withPayments(payments) .withLinks(links) .build(); connectorDDMockClient.respondOk_whenSearchPayments(GATEWAY_ACCOUNT_ID, ddConnectorSearchResult); ImmutableMap<String, String> queryParams = ImmutableMap.of( "reference", "ref", "state", "pending", "mandate_id", "mandate-id", "page", "2", "display_size", "3" ); searchPayments(queryParams) .statusCode(200) .contentType(JSON) .body("results.size()", equalTo(3)) .body("total", is(40)) .body("count", is(3)) .body("page", is(2)) .body("results[0].payment_id", Matchers.is(payments.get(0).getPayment_id())) .body("results[0].amount", Matchers.is(payments.get(0).getAmount().intValue())) .body("results[0].payment_provider", Matchers.is(payments.get(0).getPayment_provider())) .body("results[0].created_date", Matchers.is(payments.get(0).getCreated_date())) .body("results[0].description", Matchers.is(payments.get(0).getDescription())) .body("results[0].reference", Matchers.is(payments.get(0).getReference())) .body("results[0].state.status", Matchers.is(payments.get(0).getState().getStatus())) .body("results[0].state.details", Matchers.is(payments.get(0).getState().getDetails())) .body("results[0].mandate_id", Matchers.is(payments.get(0).getMandate_id())) .body("results[0].provider_id", Matchers.is(payments.get(0).getProvider_id())) .body("results[0]._links.self.href", Matchers.is(paymentLocationFor(payments.get(0).getPayment_id()))) .body("results[0]._links.self.method", Matchers.is("GET")) .body("results[0]._links.mandate.href", Matchers.is(mandateLocationFor(payments.get(0).getMandate_id()))) .body("results[0]._links.mandate.method", Matchers.is("GET")) .body("_links.next_page.href", is(expectedPaginationLink("?from_date=2016-01-01T23%3A59%3A59Z&query=next"))) .body("_links.prev_page.href", is(expectedPaginationLink("?from_date=2016-01-01T23%3A59%3A59Z&query=prev"))) .body("_links.first_page.href", is(expectedPaginationLink("?from_date=2016-01-01T23%3A59%3A59Z&query=first"))) .body("_links.last_page.href", is(expectedPaginationLink("?from_date=2016-01-01T23%3A59%3A59Z&query=last"))) .body("_links.self.href", is(expectedPaginationLink("?from_date=2016-01-01T23%3A59%3A59Z&query=self"))); } @Test public void searchPayments_validationSuccess() { String payments = aPaginatedPaymentSearchResult() .withCount(10) .withPage(2) .withTotal(20) .withPayments(aTestDirectDebitPaymentSearchResult() .buildMultiple(3)) .build(); connectorDDMockClient.respondOk_whenSearchPayments(GATEWAY_ACCOUNT_ID, payments); Map<String, String> queryParams = Map.of( "reference", "a-ref", "state", "pending", "mandate_id", "a-mandate-id", "from_date", "2016-01-01T23:59:59Z", "to_date", "2016-01-01T23:59:59Z", "page", "1", "display_size", "500"); searchPayments(queryParams) .statusCode(200) .contentType(JSON) .body("results.size()", equalTo(3)); } @Test @Parameters(method = "parametersForValidation") public void validationFailures(SearchDirectDebitPaymentsValidationParameters parameters) { given().port(app.getLocalPort()) .accept(JSON) .contentType(JSON) .header(AUTHORIZATION, "Bearer " + API_KEY) .get(GET_PATH + parameters.queryString) .then() .statusCode(HttpStatus.SC_UNPROCESSABLE_ENTITY) .body("size()", is(3)) .body("field", is(parameters.expectedErrorField)) .body("code", is(parameters.expectedErrorCode)) .body("description", is(parameters.expectedErrorMessage)); } private SearchDirectDebitPaymentsValidationParameters[] parametersForValidation() { return new SearchDirectDebitPaymentsValidationParameters[] { someParameters() .withQueryString("?reference=" + RandomStringUtils.random(256)) .withErrorField("reference") .withErrorMessage("Invalid attribute value: reference. Must be less than or equal to 255 characters length") .build(), someParameters() .withQueryString("?state=fake_state") .withErrorField("state") .withErrorMessage("Invalid attribute value: state. Must be one of created, pending, success, failed, cancelled, paidout, indemnityclaim or error") .build(), someParameters() .withQueryString("?state=PENDING") .withErrorField("state") .withErrorMessage("Invalid attribute value: state. Must be one of created, pending, success, failed, cancelled, paidout, indemnityclaim or error") .build(), someParameters() .withQueryString("?from_date=not_a_date") .withErrorField("from_date") .withErrorMessage("Invalid attribute value: from_date. Must be a valid date") .build(), someParameters() .withQueryString("?to_date=not_a_date") .withErrorField("to_date") .withErrorMessage("Invalid attribute value: to_date. Must be a valid date") .build(), someParameters() .withQueryString("?page=0") .withErrorField("page") .withErrorMessage("Invalid attribute value: page. Must be greater than or equal to 1") .build(), someParameters() .withQueryString("?display_size=0") .withErrorField("display_size") .withErrorMessage("Invalid attribute value: display_size. Must be greater than or equal to 1") .build(), someParameters() .withQueryString("?display_size=501") .withErrorField("display_size") .withErrorMessage("Invalid attribute value: display_size. Must be less than or equal to 500") .build(), }; } private String expectedPaginationLink(String queryParams) { return "http://publicapi.url" + GET_PATH + queryParams; } private ValidatableResponse searchPayments(Map<String, String> queryParams) { return given().port(app.getLocalPort()) .accept(JSON) .contentType(JSON) .header(AUTHORIZATION, "Bearer " + API_KEY) .queryParams(queryParams) .get(GET_PATH) .then(); } static class SearchDirectDebitPaymentsValidationParameters { String queryString; String expectedErrorCode; String expectedErrorField; String expectedErrorMessage; private SearchDirectDebitPaymentsValidationParameters(CreatePaymentRequestValidationParametersBuilder builder) { this.queryString = builder.queryString; this.expectedErrorCode = builder.expectedErrorCode; this.expectedErrorField = builder.expectedErrorField; this.expectedErrorMessage = builder.expectedErrorMessage; } @Override public String toString() { return "SearchDirectDebitPaymentsValidationParameters{" + "queryString='" + queryString + '\'' + ", expectedErrorCode='" + expectedErrorCode + '\'' + ", expectedErrorField='" + expectedErrorField + '\'' + ", expectedErrorMessage='" + expectedErrorMessage + '\'' + '}'; } static class CreatePaymentRequestValidationParametersBuilder { public String queryString; public String expectedErrorCode = "P0102"; public String expectedErrorField; public String expectedErrorMessage; static CreatePaymentRequestValidationParametersBuilder someParameters() { return new CreatePaymentRequestValidationParametersBuilder(); } CreatePaymentRequestValidationParametersBuilder withQueryString(String queryString) { this.queryString = queryString; return this; } CreatePaymentRequestValidationParametersBuilder withErrorCode(String errorCode) { this.expectedErrorCode= errorCode; return this; } CreatePaymentRequestValidationParametersBuilder withErrorField(String errorField) { this.expectedErrorField= errorField; return this; } CreatePaymentRequestValidationParametersBuilder withErrorMessage(String errorMessage) { this.expectedErrorMessage= errorMessage; return this; } SearchDirectDebitPaymentsValidationParameters build() { return new SearchDirectDebitPaymentsValidationParameters(this); } } } }
50.014184
193
0.608125
4bf353b7490b4a700458631719c6a9125531797d
3,750
package drzhark.mocreatures.entity.ambient; import drzhark.mocreatures.MoCreatures; import drzhark.mocreatures.entity.MoCEntityAmbient; import drzhark.mocreatures.entity.ai.EntityAIWanderMoC2; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.network.datasync.DataParameter; import net.minecraft.network.datasync.DataSerializers; import net.minecraft.network.datasync.EntityDataManager; import net.minecraft.world.World; import net.minecraft.util.ResourceLocation; public class MoCEntitySnail extends MoCEntityAmbient { private static final DataParameter<Boolean> IS_HIDDING = EntityDataManager.createKey(MoCEntitySnail.class, DataSerializers.BOOLEAN); public MoCEntitySnail(World world) { super(world); setSize(0.2F, 0.2F); } protected void initEntityAI() { this.tasks.addTask(1, (EntityAIBase)new EntityAIWanderMoC2((EntityCreature)this, 0.8D)); } protected void entityInit() { super.entityInit(); this.dataManager.register(IS_HIDDING, Boolean.valueOf(false)); } protected void applyEntityAttributes() { super.applyEntityAttributes(); getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(5.0D); getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.1D); } public boolean isMovementCeased() { return getIsHiding(); } public void selectType() { if (getType() == 0) { setType(this.rand.nextInt(6) + 1); } } public ResourceLocation getTexture() { switch (getType()) { case 1: return MoCreatures.proxy.getTexture("snaila.png"); case 2: return MoCreatures.proxy.getTexture("snailb.png"); case 3: return MoCreatures.proxy.getTexture("snailc.png"); case 4: return MoCreatures.proxy.getTexture("snaild.png"); case 5: return MoCreatures.proxy.getTexture("snaile.png"); case 6: return MoCreatures.proxy.getTexture("snailf.png"); } return MoCreatures.proxy.getTexture("snaila.png"); } public boolean getIsHiding() { return ((Boolean)this.dataManager.get(IS_HIDDING)).booleanValue(); } public void setIsHiding(boolean flag) { this.dataManager.set(IS_HIDDING, Boolean.valueOf(flag)); } public void onLivingUpdate() { super.onLivingUpdate(); if (!this.world.isRemote) { EntityLivingBase entityliving = getBoogey(3.0D); if (entityliving != null && entityliving.height > 0.5F && entityliving.width > 0.5F && canEntityBeSeen((Entity)entityliving)) { if (!getIsHiding()) { setIsHiding(true); } getNavigator().clearPath(); } else { setIsHiding(false); } if (getIsHiding() && getType() > 4) { setIsHiding(false); } } } public void fall(float f, float f1) {} public void onUpdate() { super.onUpdate(); if (getIsHiding()) { this.prevRenderYawOffset = this.renderYawOffset = this.rotationYaw = this.prevRotationYaw; } } protected Item getDropItem() { return Items.SLIME_BALL; } public boolean isOnLadder() { return this.collidedHorizontally; } public boolean climbing() { return (!this.onGround && isOnLadder()); } public void jump() {} } /* Location: C:\Users\mami\files\games\minecraft\sneakyrp\mocreatures-fix\DrZharks MoCreatures Mod-12.0.5-deobf.jar!\drzhark\mocreatures\entity\ambient\MoCEntitySnail.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
26.408451
185
0.701333
ea68beca7048fa3cf2f7f35fbe89502b78d26845
1,220
package ru.job4j.collections; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class NotifyAccountTest { @Test public void whenNoDups() { HashSet<Account> setOfAccs = new HashSet<>( Arrays.asList( new Account("460611", "Stanford Pines", "ef2346c85ab"), new Account("460512", "Bill Cipher", "ef2346d85ab") )); List<Account> listOfAccs = Arrays.asList( new Account("460611", "Stanford Pines", "ef2346c85ab"), new Account("460512", "Bill Cipher", "ef2346d85ab") ); assertThat(NotifyAccount.send(listOfAccs), is(setOfAccs)); } @Test public void whenHasDups() { List<Account> listOfAccs = Arrays.asList( new Account("460611", "Stanford Pines", "ef2346c85ab"), new Account("460512", "Bill Cipher", "ef2346d85ab"), new Account("460512", "Bill Cipher", "ed1346e85ab") ); HashSet<Account> setOfAccs = new HashSet<>( Arrays.asList( new Account("460611", "Stanford Pines", "ef2346c85ab"), new Account("460512", "Bill Cipher", "ef2346d85ab") )); assertThat(NotifyAccount.send(listOfAccs), is(setOfAccs)); } }
29.756098
61
0.690984
b03299bf5b33c65a9ce616b9c0d7b078b87ce072
597
package router.client.api2; import java.util.Objects; import javax.annotation.Nonnull; class OnLeaveCallbackAsyncAdapter implements OnLeaveCallbackAsync { private final OnLeaveCallback _callback; OnLeaveCallbackAsyncAdapter( @Nonnull final OnLeaveCallback callback ) { _callback = Objects.requireNonNull( callback ); } @Override public void onLeave( @Nonnull final RouteContext context, @Nonnull final Route route, @Nonnull final OnLeaveControl control ) { _callback.onLeave( context, route ); control.proceed(); } }
23.88
72
0.708543
41e83d09d4c7f8c86f07e44fd38d100eff4ea823
3,048
package com.ant.auto.core; import java.io.File; import java.util.HashMap; import java.util.Map; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.firefox.internal.ProfilesIni; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.remote.DesiredCapabilities; import com.ant.auto.Consts; /** * 装配浏览器 * * @author sekift */ public class AssembleBrowser { /** * 装配chrome浏览器 * * @param browserDir * @return */ public static WebDriver setChrome(String browserDir) { System.setProperty(Consts.Driver.CHROME_DRIVER, browserDir); return new ChromeDriver(); } /** * 装配chrome浏览器 * * @param browserDir * @param mobile * @return */ public static WebDriver setChromeAsPhone(String browserDir, String mobile) { System.setProperty(Consts.Driver.CHROME_DRIVER, browserDir); Map<String, String> mobileEmulation = new HashMap<>(4); // 模拟手机端 mobileEmulation.put("deviceName", mobile); Map<String, Object> chromeOptions = new HashMap<>(4); chromeOptions.put("mobileEmulation", mobileEmulation); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); return new ChromeDriver(capabilities); } /** * 装配firefox浏览器,带配置启动 * * @param dir * @param browserDir * @param defaultConf * @return */ public static WebDriver setFirefox(String dir, String browserDir, boolean defaultConf) { System.setProperty(Consts.Driver.GECKO_DRIVER, dir); File pathBinary = new File(browserDir); FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary); FirefoxProfile firefoxProfile = new FirefoxProfile(); if (defaultConf) { ProfilesIni pi = new ProfilesIni(); firefoxProfile = pi.getProfile("default"); } //20180713 取消旧写法,改用新写法 //WebDriver driver = new FirefoxDriver(firefoxBinary, firefoxProfile); FirefoxOptions options = new FirefoxOptions().setBinary(firefoxBinary).setProfile(firefoxProfile); return new FirefoxDriver(options); } /** * 装配opera浏览器 * * @param dir * @param browserDir * @return */ public static WebDriver setOpera(String dir, String browserDir) { System.setProperty(Consts.Driver.OPERA_DRIVER, dir); ChromeOptions options = new ChromeOptions(); options.setBinary(browserDir); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(ChromeOptions.CAPABILITY, options); return new OperaDriver(capabilities); } }
32.084211
106
0.688976
f4364e2fc92a45a0b4420d13732315d0fd1ce282
1,057
package webserver.model.dao; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.util.Date; @Entity @Data public class UserLink { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String url; private Long groupId; private Long projectId; private Long userId; private boolean isCommon; private boolean isLocal; private boolean isPublic; private boolean isDeleted; private int type; private String type_name; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") private Date createTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") private Date updateTime; }
25.780488
68
0.733207
c6942fcb96b6c21949a07eaee1594ce4759b9dd0
5,539
/* * JTok * A configurable tokenizer implemented in Java * * (C) 2003 - 2014 DFKI Language Technology Lab http://www.dfki.de/lt * Author: Joerg Steffen, steffen@dfki.de * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package de.dfki.lt.tools.tokenizer.output; import de.dfki.lt.tools.tokenizer.PunctDescription; /** * Represents a token with its type and surface image. * * @author Joerg Steffen, DFKI */ public class Token { // the Penn Treebank replacements for brackets: private static final String LRB = "-LRB-"; private static final String RRB = "-RRB-"; private static final String LSB = "-LSB-"; private static final String RSB = "-RSB-"; private static final String LCB = "-LCB-"; private static final String RCB = "-RCB-"; // start index of the token private int startIndex; // end index of the token private int endIndex; // type of the token private String type; // surface image of the token private String image; /** * Creates a new instance of {@link Token}. */ public Token() { this.setStartIndex(0); this.setEndIndex(0); this.setType(new String()); this.setImage(new String()); } /** * Creates a new instance of {@link Token} for the given start index, end index, type and surface * image. * * @param startIndex * the start index * @param endIndex * the end index * @param type * the type * @param image * the surface image */ public Token(int startIndex, int endIndex, String type, String image) { this.setStartIndex(startIndex); this.setEndIndex(endIndex); this.setType(type); this.setImage(image); } /** * @return the start index */ public int getStartIndex() { return this.startIndex; } /** * @param startIndex * the start index to set */ public void setStartIndex(int startIndex) { this.startIndex = startIndex; } /** * @return the end index */ public int getEndIndex() { return this.endIndex; } /** * @param endIndex * the end index to set */ public void setEndIndex(int endIndex) { this.endIndex = endIndex; } /** * @return the token type */ public String getType() { return this.type; } /** * @param type * the token type to set */ public void setType(String type) { this.type = type; } /** * @return the surface image */ public String getImage() { return this.image; } /** * @param image * the surface image to set */ public void setImage(String image) { this.image = image; } /** * Returns the Penn Treebank surface image of the token if a Penn Treebank replacement took place, * {@code null} otherwise. * * @return the surface image as the result of the Penn Treebank token replacement or {@code null} */ public String getPtbImage() { return applyPtbFormat(this.image, this.type); } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder result = new StringBuilder( String.format(" Token: %-15s\tType: %s\tStart: %s\tEnd: %s", String.format("\"%s\"", this.getImage()), this.getType(), this.getStartIndex(), this.getEndIndex())); String ptbImage = applyPtbFormat(this.image, this.type); if (null != ptbImage) { result.append(String.format("\tPTB: \"%s\"", ptbImage)); } result.append(String.format("%n")); return result.toString(); } /** * This applies some replacements used in the Penn Treebank format to the given token image of the * given type. * * @param image * the token image * @param type * the type * @return a modified string or {@code null} if no replacement took place */ public static String applyPtbFormat(String image, String type) { String result = null; if (type.equals(PunctDescription.OPEN_BRACKET)) { if (image.equals("(")) { result = LRB; } else if (image.equals("[")) { result = LSB; } else if (image.equals("{")) { result = LCB; } } else if (type.equals(PunctDescription.CLOSE_BRACKET)) { if (image.equals(")")) { result = RRB; } else if (image.equals("]")) { result = RSB; } else if (image.equals("}")) { result = RCB; } } else if (type.equals(PunctDescription.OPEN_PUNCT)) { result = "``"; } else if (type.equals(PunctDescription.CLOSE_PUNCT)) { result = "''"; } else if (image.contains("/")) { result = image.replace("/", "\\/"); } else if (image.contains("*")) { result = image.replace("*", "\\*"); } return result; } }
22.608163
100
0.61058
4507b028f4c88d1e92e0319d3c3ccb265259b47f
2,513
package net.futureclient.asm.transformer.util; import com.google.common.collect.ImmutableMap; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import java.lang.annotation.Annotation; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Created by Babbaj on 5/26/2018. */ public class AnnotationInfo { private final Class<? extends Annotation> annotationClazz; private final ImmutableMap<String, ?> valueMap; public static AnnotationInfo fromAsm(ClassNode node, Class<? extends Annotation> clazz) { return node.visibleAnnotations.stream() .filter(annot -> annot.desc.equals('L' + Type.getInternalName(clazz) + ';')) .findFirst() .map(AnnotationInfo::fromAsm) .orElseThrow(() -> new IllegalArgumentException("ClassNode does not contain annotation " + clazz.getName())); } @SuppressWarnings("unchecked") public static AnnotationInfo fromAsm(AnnotationNode node) { if (!node.desc.matches("(?:L).+(?:;)")) throw new IllegalArgumentException("Invalid ASM Annotation Class Name: " + node.desc); String className = node.desc.substring(1, node.desc.length()-1); // strip 'L' and ';' Class<?> clazz; try { clazz = Class.forName(className.replace("/", ".")); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } ImmutableMap<String, ?> map = ImmutableMap.copyOf(createValueMap(node)); return new AnnotationInfo((Class<? extends Annotation>)clazz, map); } private AnnotationInfo(Class<? extends Annotation> clazz, ImmutableMap<String, ?> valueMap) { this.annotationClazz = clazz; this.valueMap = valueMap; } @SuppressWarnings("unchecked") public <T> T getValue(String name) { return (T)valueMap.get(name); } public Class<?> getAnnotationClass() { return this.annotationClazz; } /** * Creates a name-value map from an annotation's value list * * See {@link org.objectweb.asm.tree.AnnotationNode#values} */ private static Map<String, ?> createValueMap(AnnotationNode annotation) { Map<String, Object> out = new HashMap<>(); Iterator<Object> iter = annotation.values.iterator(); while (iter.hasNext()) { out.put((String)iter.next(), iter.next()); } return out; } }
35.394366
134
0.651015
44467ab43cc8166dc38dfd8ba84d997d8223b3fe
11,188
package us.dot.its.jpo.ode.traveler; import org.json.JSONObject; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import us.dot.its.jpo.ode.OdeProperties; import us.dot.its.jpo.ode.context.AppContext; import us.dot.its.jpo.ode.model.Asn1Encoding; import us.dot.its.jpo.ode.model.Asn1Encoding.EncodingRule; import us.dot.its.jpo.ode.model.OdeAsdPayload; import us.dot.its.jpo.ode.model.OdeMsgMetadata; import us.dot.its.jpo.ode.model.OdeMsgPayload; import us.dot.its.jpo.ode.model.OdeTimPayload; import us.dot.its.jpo.ode.model.SerialId; import us.dot.its.jpo.ode.plugin.RoadSideUnit.RSU; import us.dot.its.jpo.ode.plugin.SNMP; import us.dot.its.jpo.ode.plugin.ServiceRequest; import us.dot.its.jpo.ode.plugin.SituationDataWarehouse.SDW; import us.dot.its.jpo.ode.plugin.ieee1609dot2.Ieee1609Dot2Content; import us.dot.its.jpo.ode.plugin.ieee1609dot2.Ieee1609Dot2Data; import us.dot.its.jpo.ode.plugin.ieee1609dot2.Ieee1609Dot2DataTag; import us.dot.its.jpo.ode.plugin.j2735.DdsAdvisorySituationData; import us.dot.its.jpo.ode.plugin.j2735.J2735DSRCmsgID; import us.dot.its.jpo.ode.plugin.j2735.J2735MessageFrame; import us.dot.its.jpo.ode.plugin.j2735.builders.GeoRegionBuilder; import us.dot.its.jpo.ode.plugin.j2735.builders.TravelerMessageFromHumanToAsnConverter; import us.dot.its.jpo.ode.plugin.j2735.timstorage.MessageFrame; import us.dot.its.jpo.ode.plugin.j2735.timstorage.TravelerInputData; import us.dot.its.jpo.ode.util.JsonUtils; import us.dot.its.jpo.ode.util.JsonUtils.JsonUtilsException; import us.dot.its.jpo.ode.util.XmlUtils; import us.dot.its.jpo.ode.util.XmlUtils.XmlUtilsException; public class TimTransmogrifier { private static final String ADVISORY_SITUATION_DATA = "AdvisorySituationData"; private static final String MESSAGE_FRAME = "MessageFrame"; public static final String RSUS_STRING = "rsus"; public static final String REQUEST_STRING = "request"; public static class TimTransmogrifierException extends Exception { private static final long serialVersionUID = -923627369025468080L; public TimTransmogrifierException(String message) { super(message); } } private TimTransmogrifier() { throw new UnsupportedOperationException(); } public static String obfuscateRsuPassword(String message) { return message.replaceAll("\"rsuPassword\": *\".*?\"", "\"rsuPassword\":\"*\""); } public static DdsAdvisorySituationData buildASD(ServiceRequest serviceRequest) throws TimTransmogrifierException { Ieee1609Dot2DataTag ieeeDataTag = new Ieee1609Dot2DataTag(); Ieee1609Dot2Data ieee = new Ieee1609Dot2Data(); Ieee1609Dot2Content ieeeContent = new Ieee1609Dot2Content(); J2735MessageFrame j2735Mf = new J2735MessageFrame(); MessageFrame mf = new MessageFrame(); mf.setMessageFrame(j2735Mf); ieeeContent.setUnsecuredData(mf); ieee.setContent(ieeeContent); ieeeDataTag.setIeee1609Dot2Data(ieee); byte sendToRsu = serviceRequest.getRsus() != null ? DdsAdvisorySituationData.RSU : DdsAdvisorySituationData.NONE; byte distroType = (byte) (DdsAdvisorySituationData.IP | sendToRsu); SNMP snmp = serviceRequest.getSnmp(); SDW sdw = serviceRequest.getSdw(); DdsAdvisorySituationData asd = null; if (null != sdw) { try { // take deliverystart and stop times from SNMP object, if present // else take from SDW object if (null != snmp) { asd = new DdsAdvisorySituationData() .setAsdmDetails(snmp.getDeliverystart(), snmp.getDeliverystop(), distroType, ieeeDataTag) .setServiceRegion(GeoRegionBuilder.ddsGeoRegion(sdw.getServiceRegion())) .setTimeToLive(sdw.getTtl()).setGroupID(sdw.getGroupID()).setRecordID(sdw.getRecordId()); } else { asd = new DdsAdvisorySituationData() .setAsdmDetails(sdw.getDeliverystart(), sdw.getDeliverystop(), distroType, ieeeDataTag) .setServiceRegion(GeoRegionBuilder.ddsGeoRegion(sdw.getServiceRegion())) .setTimeToLive(sdw.getTtl()).setGroupID(sdw.getGroupID()).setRecordID(sdw.getRecordId()); } } catch (Exception e) { throw new TimTransmogrifierException("Failed to build AdvisorySituationData: " + e.getMessage()); } } return asd; } public static String convertToXml(DdsAdvisorySituationData asd, ObjectNode encodableTidObj, OdeMsgMetadata timMetadata, SerialId serialIdJ2735) throws JsonUtilsException, XmlUtilsException { TravelerInputData inOrderTid = (TravelerInputData) JsonUtils.jacksonFromJson(encodableTidObj.toString(), TravelerInputData.class); ObjectNode inOrderTidObj = JsonUtils.toObjectNode(inOrderTid.toJson()); ObjectNode timObj = (ObjectNode) inOrderTidObj.get("tim"); // Create valid payload from scratch OdeMsgPayload payload = null; ObjectNode dataBodyObj = JsonUtils.newNode(); if (null != asd) { ObjectNode asdObj = JsonUtils.toObjectNode(asd.toJson()); ObjectNode mfBodyObj = (ObjectNode) asdObj.findValue(MESSAGE_FRAME); mfBodyObj.put("messageId", J2735DSRCmsgID.TravelerInformation.getMsgID()); mfBodyObj.set("value", (ObjectNode) JsonUtils.newNode().set(TravelerMessageFromHumanToAsnConverter.TRAVELER_INFORMATION, timObj)); dataBodyObj.set(ADVISORY_SITUATION_DATA, asdObj); payload = new OdeAsdPayload(asd); } else { // Build a MessageFrame ObjectNode mfBodyObj = JsonUtils.newNode(); mfBodyObj.put("messageId", J2735DSRCmsgID.TravelerInformation.getMsgID()); mfBodyObj.set("value", (ObjectNode) JsonUtils.newNode().set(TravelerMessageFromHumanToAsnConverter.TRAVELER_INFORMATION, timObj)); dataBodyObj = (ObjectNode) JsonUtils.newNode().set(MESSAGE_FRAME, mfBodyObj); payload = new OdeTimPayload(); payload.setDataType(MESSAGE_FRAME); } ObjectNode payloadObj = JsonUtils.toObjectNode(payload.toJson()); payloadObj.set(AppContext.DATA_STRING, dataBodyObj); // Create a valid metadata from scratch OdeMsgMetadata metadata = new OdeMsgMetadata(payload); metadata.setSerialId(serialIdJ2735); metadata.setRecordGeneratedBy(timMetadata.getRecordGeneratedBy()); metadata.setRecordGeneratedAt(timMetadata.getRecordGeneratedAt()); metadata.setSchemaVersion(timMetadata.getSchemaVersion()); ObjectNode metaObject = JsonUtils.toObjectNode(metadata.toJson()); ObjectNode request = (ObjectNode) inOrderTidObj.get(REQUEST_STRING); metaObject.set(REQUEST_STRING, request); if (request.has(RSUS_STRING)) { convertRsusArray(request); } // Add 'encodings' array to metadata convertEncodingsArray(asd, metaObject); ObjectNode message = JsonUtils.newNode(); message.set(AppContext.METADATA_STRING, metaObject); message.set(AppContext.PAYLOAD_STRING, payloadObj); ObjectNode root = JsonUtils.newNode(); root.set(AppContext.ODE_ASN1_DATA, message); // Convert to XML String outputXml = XmlUtils.toXmlStatic(root); // Fix tagnames by String replacements String fixedXml = outputXml.replaceAll("tcontent>", "content>");// workaround // for the // "content" // reserved // name fixedXml = fixedXml.replaceAll("llong>", "long>"); // workaround for // "long" being a type // in java fixedXml = fixedXml.replaceAll("node_LL", "node-LL"); fixedXml = fixedXml.replaceAll("node_XY", "node-XY"); fixedXml = fixedXml.replaceAll("node_LatLon>", "node-LatLon>"); fixedXml = fixedXml.replaceAll("nodeLL>", "NodeLL>"); fixedXml = fixedXml.replaceAll("nodeXY>", "NodeXY>"); // workarounds for self-closing tags fixedXml = fixedXml.replaceAll(TravelerMessageFromHumanToAsnConverter.EMPTY_FIELD_FLAG, ""); fixedXml = fixedXml.replaceAll(TravelerMessageFromHumanToAsnConverter.BOOLEAN_OBJECT_TRUE, "<true />"); fixedXml = fixedXml.replaceAll(TravelerMessageFromHumanToAsnConverter.BOOLEAN_OBJECT_FALSE, "<false />"); // remove the surrounding <ObjectNode></ObjectNode> fixedXml = fixedXml.replace("<ObjectNode>", ""); fixedXml = fixedXml.replace("</ObjectNode>", ""); return fixedXml; } private static void convertEncodingsArray(DdsAdvisorySituationData asd, ObjectNode metaObject) throws JsonUtilsException { ArrayNode encodings = buildEncodings(asd); ObjectNode enc = XmlUtils.createEmbeddedJsonArrayForXmlConversion(AppContext.ENCODINGS_STRING, encodings); metaObject.set(AppContext.ENCODINGS_STRING, enc); } private static void convertRsusArray(ObjectNode request) { // Convert 'rsus' JSON array to XML array ObjectNode rsus = XmlUtils.createEmbeddedJsonArrayForXmlConversion(RSUS_STRING, (ArrayNode) request.get(RSUS_STRING)); request.set(RSUS_STRING, rsus); } private static ArrayNode buildEncodings(DdsAdvisorySituationData asd) throws JsonUtilsException { ArrayNode encodings = JsonUtils.newArrayNode(); encodings.add(buildEncodingNode(MESSAGE_FRAME, MESSAGE_FRAME, EncodingRule.UPER)); if (null != asd) { encodings.add(buildEncodingNode("Ieee1609Dot2Data", "Ieee1609Dot2Data", EncodingRule.COER)); encodings.add(buildEncodingNode(ADVISORY_SITUATION_DATA, ADVISORY_SITUATION_DATA, EncodingRule.UPER)); } return encodings; } public static void updateRsuCreds(RSU rsu, OdeProperties odeProperties) { if (rsu.getRsuUsername() == null || rsu.getRsuUsername().isEmpty()) { rsu.setRsuUsername(odeProperties.getRsuUsername()); } if (rsu.getRsuPassword() == null || rsu.getRsuPassword().isEmpty()) { rsu.setRsuPassword(odeProperties.getRsuPassword()); } } public static JsonNode buildEncodingNode(String name, String type, EncodingRule rule) throws JsonUtilsException { Asn1Encoding mfEnc = new Asn1Encoding(name, type, rule); return JsonUtils.toObjectNode(mfEnc.toJson()); } public static JSONObject createOdeTimData(JSONObject timData) { JSONObject metadata = timData.getJSONObject(AppContext.METADATA_STRING); metadata.put("payloadType", OdeTimPayload.class.getName()); metadata.remove(AppContext.ENCODINGS_STRING); JSONObject payload = timData.getJSONObject(AppContext.PAYLOAD_STRING); payload.put(AppContext.DATA_TYPE_STRING, TravelerMessageFromHumanToAsnConverter.TRAVELER_INFORMATION); return timData; } }
45.112903
139
0.698427
bb53d4040818afc1c23dff67acad38212214d8ca
3,881
package gov.hhs.cms.bluebutton.texttofhir; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.List; import org.hl7.fhir.dstu21.model.Bundle; import org.hl7.fhir.dstu21.model.Patient; import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.Assert; import org.junit.Test; import ca.uhn.fhir.rest.client.GenericClient; import ca.uhn.fhir.rest.gclient.ITransaction; import ca.uhn.fhir.rest.gclient.ITransactionTyped; import gov.hhs.cms.bluebutton.texttofhir.parsing.TextFile; import gov.hhs.cms.bluebutton.texttofhir.parsing.TextFileParseException; import gov.hhs.cms.bluebutton.texttofhir.parsing.TextFileProcessor; import gov.hhs.cms.bluebutton.texttofhir.transform.TextFileTransformer; import mockit.Invocation; import mockit.Mock; import mockit.MockUp; /** * Unit tests for {@link TextToFhirApp}. */ public final class TextToFhirAppTest { // TODO start as part of test private static final String FHIR_URL = "http://localhost:8080/hapi-fhir/baseDstu2"; @Test public void quickRun() throws TextFileParseException, IOException { // Create the mock data that we'll flow through. TextFile parseResult = new TextFile(ZonedDateTime.now()); List<IBaseResource> transformResult = Arrays.asList(new Patient()); /* * Specify all of the mock objects to use. Creating these accomplishes * two things: 1) JMockit will register each of these as they're created * and then verify that they're all used at some point in this test * case, and 2) JMockit will intercept any calls to matching "real" * objects in this test case and replace those calls with these mocks. */ new MockUp<TextFileProcessor>() { @Mock TextFile parse(InputStream textFileStream) { return parseResult; } }; new MockUp<TextFileTransformer>() { @Mock List<IBaseResource> transform(TextFile inputData) { /* * Verify that the TextFile passed in is the one produced by the * (mock) processor. */ Assert.assertSame(parseResult, inputData); return transformResult; } }; MockUp<ITransactionTyped<Bundle>> fhirTransactionTyped = new MockUp<ITransactionTyped<Bundle>>() { @Mock Bundle execute(Invocation invocation) { return new Bundle(); } }; MockUp<ITransaction> fhirTransaction = new MockUp<ITransaction>() { @SuppressWarnings("unchecked") @Mock <T extends IBaseBundle> ITransactionTyped<T> withBundle(Invocation invocation, T theBundle) { /* * Verify that the Bundle contains the resource(s) that were * produced by the (mock) transformer. */ Bundle bundleTyped = (Bundle) theBundle; Assert.assertNotNull(bundleTyped); Assert.assertEquals(transformResult.size(), bundleTyped.getEntry().size()); Assert.assertSame(transformResult.get(0), bundleTyped.getEntry().get(0).getResource()); return (ITransactionTyped<T>) fhirTransactionTyped.getMockInstance(); } }; new MockUp<GenericClient>() { @Mock ITransaction transaction(Invocation invocation) { return fhirTransaction.getMockInstance(); } }; // Create the fake (empty) file to run against. Path inputTextFile = Files.createTempFile(null, ".txt"); inputTextFile.toFile().deleteOnExit(); // Run the application (will use all mocks defined above). TextToFhirApp.main(new String[] { "--server", FHIR_URL, inputTextFile.toAbsolutePath().toString() }); /* * If we got here, the test case passed. Yay! Most of the verification * is handled by JMockit just ensuring that the mocks were all used. * There's some additional assertions inside those mocks, too. */ } }
35.281818
104
0.719145
262f077b9014f03cc663cc8a81326a62f67f8eb3
1,708
package com.VocetSoft.ChatApp; import java.util.Scanner; import com.VocetSoft.Client.Client; import com.VocetSoft.Server.Server; public class Main { public static void main(String[] args) { String cmd = null; Scanner scanner = new Scanner(System.in); showMsg("Choose 'Server' or 'Client'"); cmd = scanner.next(); Server server = null; Client client = null; if (cmd.equals("Server")) { showMsg("Server selected"); showMsg("Enter port"); int port = scanner.nextInt(); showMsg("Listening out for a client....."); server = new Server(port); final Server server2 = server; Runnable r = new Runnable() { @Override public void run() { server2.msgListener(); } }; Thread t = new Thread(r,""); t.start(); server.chat(); } if (cmd.equals("Client")) { showMsg("Client Selected"); showMsg("Enter port"); int port = scanner.nextInt(); showMsg("Enter host's address"); String hostName = scanner.next(); client = new Client(port,hostName); final Client client2 = client; Runnable r = new Runnable() { @Override public void run() { client2.msgListener(); } }; Thread t = new Thread(r,""); t.start(); client.chat(); } } public static void showMsg(String msg) { System.out.println(msg); } }
25.878788
55
0.484192
fc8fc591c94d0c142462def1ac67e8c8bdbfe7db
3,036
package com.etuspace.firebase.example.fireeats.java.LabFragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.etuspace.firebase.example.fireeats.java.adapter.UsersAdapter; import com.etuspace.firebase.example.fireeats.R; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.Query; import com.jaredrummler.materialspinner.MaterialSpinner; public class FourLabFragment extends Fragment implements UsersAdapter.OnUserSelectedListener { private FirebaseFirestore mFirestore; private Query mQuery; private ViewGroup mEmptyView; private UsersAdapter mAdapter; RecyclerView mUsersRecycle; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //return super.onCreateView(inflater, container, savedInstanceState); View rootView = inflater.inflate(R.layout.fragment_four_lab, container, false); MaterialSpinner spinnerGroup = (MaterialSpinner) getActivity().findViewById(R.id.spinnerGroup); mUsersRecycle = rootView.findViewById(R.id.recycler_four_lab); mEmptyView = rootView.findViewById(R.id.viewEmptyUsers4); mFirestore = FirebaseFirestore.getInstance(); mQuery = mFirestore.collection("users").whereEqualTo("group",spinnerGroup.getText().toString()); mAdapter = new UsersAdapter(mQuery, this, 4) { @Override protected void onDataChanged() { // Show/hide content if the query returns empty. if (getItemCount() == 0) { mUsersRecycle.setVisibility(View.GONE); mEmptyView.setVisibility(View.VISIBLE); } else { mUsersRecycle.setVisibility(View.VISIBLE); mEmptyView.setVisibility(View.GONE); } } @Override protected void onError(FirebaseFirestoreException e) { // Show a snackbar on errors } }; mUsersRecycle.setLayoutManager(new LinearLayoutManager(rootView.getContext())); mUsersRecycle.setAdapter(mAdapter); return rootView; } @Override public void onStart() { super.onStart(); // Start listening for Firestore updates if (mAdapter != null) { mAdapter.startListening(); } } @Override public void onStop() { super.onStop(); if (mAdapter != null) { mAdapter.stopListening(); } } @Override public void onRestaurantSelected(DocumentSnapshot user) { } }
29.192308
104
0.669631
fb1694b44d278b2093dd8990af737034cc18ebb7
1,281
package org.songzxdev.leetcode.week05; //你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上 //被小偷闯入,系统会自动报警。 // // 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 // // 示例 1: // // 输入: [1,2,3,1] //输出: 4 //解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。 //  偷窃到的最高金额 = 1 + 3 = 4 。 // // 示例 2: // // 输入: [2,7,9,3,1] //输出: 12 //解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。 //  偷窃到的最高金额 = 2 + 9 + 1 = 12 。 // // Related Topics 动态规划 //leetcode submit region begin(Prohibit modification and deletion) public class LeetCode_198_1034 { /** * 题目:198.打家劫舍(https://leetcode-cn.com/problems/house-robber/) * 学号:1034(五期一班三组) * @param nums * @return */ public int rob(int[] nums) { if (nums != null && nums.length > 0) { int n = nums.length; int[][] loot = new int[n][2]; loot[0][0] = 0; loot[0][1] = nums[0]; for (int i = 1; i < n; i++) { loot[i][0] = Math.max(loot[i - 1][0], loot[i - 1][1]); loot[i][1] = loot[i - 1][0] + nums[i]; } return Math.max(loot[n - 1][0], loot[n - 1][1]); } return 0; } } //leetcode submit region end(Prohibit modification and deletion)
26.142857
80
0.525371
cedf3d177331383ff92cee52e57fe5df9d82f097
1,931
/** * Copyright 2018 Nikita Koksharov * * 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.redisson.misc; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.redisson.api.RedissonClient; import org.redisson.api.annotation.RInject; /** * * @author Nikita Koksharov * */ public class Injector { public static void inject(Object task, RedissonClient redisson) { List<Field> allFields = new ArrayList<Field>(); Class<?> clazz = task.getClass(); while (true) { if (clazz != null) { Field[] fields = clazz.getDeclaredFields(); allFields.addAll(Arrays.asList(fields)); } else { break; } if (clazz.getSuperclass() != Object.class) { clazz = clazz.getSuperclass(); } else { clazz = null; } } for (Field field : allFields) { if (RedissonClient.class.isAssignableFrom(field.getType()) && field.isAnnotationPresent(RInject.class)) { field.setAccessible(true); try { field.set(task, redisson); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } } } }
30.171875
75
0.593993
6ba37d3d93a40ad07a700d42e2a69fbbc24b695f
10,796
package org.infinispan.lock.singlelock; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import org.infinispan.Cache; import org.infinispan.commands.VisitableCommand; import org.infinispan.commands.tx.CommitCommand; import org.infinispan.commands.tx.PrepareCommand; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.distribution.MagicKey; import org.infinispan.remoting.rpc.RpcManager; import org.infinispan.test.MultipleCacheManagersTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.CleanupAfterMethod; import org.infinispan.transaction.impl.TransactionTable; import org.infinispan.transaction.lookup.EmbeddedTransactionManagerLookup; import org.infinispan.transaction.tm.EmbeddedTransaction; import org.infinispan.transaction.tm.EmbeddedTransactionManager; import org.infinispan.tx.dld.ControlledRpcManager; import org.infinispan.util.ControlledConsistentHashFactory; import org.testng.annotations.Test; /** * Test what happens if the originator becomes an owner during a prepare or commit RPC. * @since 5.2 */ @Test(groups = "functional", testName = "lock.singlelock.OriginatorBecomesOwnerLockTest") @CleanupAfterMethod public class OriginatorBecomesOwnerLockTest extends MultipleCacheManagersTest { private ConfigurationBuilder configurationBuilder; private static final int ORIGINATOR_INDEX = 0; private static final int OTHER_INDEX = 1; private static final int KILLED_INDEX = 2; private Cache<Object, String> originatorCache; private Cache<Object, String> killedCache; private Cache<Object, String> otherCache; // Pseudo-configuration // TODO Test fails (expected RollbackException isn't raised) if waitForStateTransfer == false because of https://issues.jboss.org/browse/ISPN-2510 private boolean waitForStateTransfer = true; // TODO Tests fails with SuspectException if stopCacheOnly == false because of https://issues.jboss.org/browse/ISPN-2402 private boolean stopCacheOnly = true; @Override protected void createCacheManagers() throws Throwable { configurationBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, true, true); configurationBuilder.transaction().transactionManagerLookup(new EmbeddedTransactionManagerLookup()); configurationBuilder.clustering().remoteTimeout(30000, TimeUnit.MILLISECONDS); configurationBuilder.clustering().hash().l1().disable(); configurationBuilder.locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis()); configurationBuilder.clustering().stateTransfer().fetchInMemoryState(true); ControlledConsistentHashFactory consistentHashFactory = new ControlledConsistentHashFactory.Default(new int[][]{{KILLED_INDEX, ORIGINATOR_INDEX}, {KILLED_INDEX, OTHER_INDEX}}); configurationBuilder.clustering().hash().numSegments(2).consistentHashFactory(consistentHashFactory); createCluster(configurationBuilder, 3); waitForClusterToForm(); originatorCache = cache(ORIGINATOR_INDEX); killedCache = cache(KILLED_INDEX); otherCache = cache(OTHER_INDEX); // Set up the consistent hash after node 1 is killed consistentHashFactory.setOwnerIndexes(new int[][]{{ORIGINATOR_INDEX, OTHER_INDEX}, {OTHER_INDEX, ORIGINATOR_INDEX}}); // TODO Add another test method with ownership changing from [KILLED_INDEX, OTHER_INDEX] to [ORIGINATOR_INDEX, OTHER_INDEX] // i.e. the originator is a non-owner at first, and becomes the primary owner when the prepare is retried } public void testOriginatorBecomesPrimaryOwnerDuringPrepare() throws Exception { Object key = new MagicKey("primary", cache(KILLED_INDEX), cache(ORIGINATOR_INDEX)); testLockMigrationDuringPrepare(key); } public void testOriginatorBecomesBackupOwnerDuringPrepare() throws Exception { Object key = new MagicKey("backup", cache(KILLED_INDEX), cache(OTHER_INDEX)); testLockMigrationDuringPrepare(key); } private void testLockMigrationDuringPrepare(final Object key) throws Exception { ControlledRpcManager controlledRpcManager = installControlledRpcManager(PrepareCommand.class); final EmbeddedTransactionManager tm = embeddedTm(ORIGINATOR_INDEX); Future<EmbeddedTransaction> f = fork(() -> { tm.begin(); originatorCache.put(key, "value"); EmbeddedTransaction tx = tm.getTransaction(); boolean success = tx.runPrepare(); assertTrue(success); tm.suspend(); return tx; }); // Allow the tx thread to send the prepare command to the owners Thread.sleep(2000); log.trace("Lock transfer happens here"); killCache(); log.trace("Allow the prepare RPC to proceed"); controlledRpcManager.stopBlocking(); // Ensure the prepare finished on the other node EmbeddedTransaction tx = f.get(); log.tracef("Prepare finished"); checkNewTransactionFails(key); log.trace("About to commit existing transactions."); tm.resume(tx); tx.runCommit(false); // read the data from the container, just to make sure all replicas are correctly set checkValue(key, "value"); } public void testOriginatorBecomesPrimaryOwnerAfterPrepare() throws Exception { Object key = new MagicKey("primary", cache(KILLED_INDEX), cache(ORIGINATOR_INDEX)); testLockMigrationAfterPrepare(key); } public void testOriginatorBecomesBackupOwnerAfterPrepare() throws Exception { Object key = new MagicKey("backup", cache(KILLED_INDEX), cache(OTHER_INDEX)); testLockMigrationAfterPrepare(key); } private void testLockMigrationAfterPrepare(Object key) throws Exception { final EmbeddedTransactionManager tm = embeddedTm(ORIGINATOR_INDEX); tm.begin(); originatorCache.put(key, "value"); EmbeddedTransaction tx = tm.getTransaction(); boolean prepareSuccess = tx.runPrepare(); assert prepareSuccess; tm.suspend(); log.trace("Lock transfer happens here"); killCache(); checkNewTransactionFails(key); log.trace("About to commit existing transaction."); tm.resume(tx); tx.runCommit(false); // read the data from the container, just to make sure all replicas are correctly set checkValue(key, "value"); } public void testOriginatorBecomesPrimaryOwnerDuringCommit() throws Exception { Object key = new MagicKey("primary", cache(KILLED_INDEX), cache(ORIGINATOR_INDEX)); testLockMigrationDuringCommit(key); } public void testOriginatorBecomesBackupOwnerDuringCommit() throws Exception { Object key = new MagicKey("backup", cache(KILLED_INDEX), cache(OTHER_INDEX)); testLockMigrationDuringCommit(key); } private void testLockMigrationDuringCommit(final Object key) throws Exception { ControlledRpcManager controlledRpcManager = installControlledRpcManager(CommitCommand.class); final EmbeddedTransactionManager tm = embeddedTm(ORIGINATOR_INDEX); Future<EmbeddedTransaction> f = fork(() -> { tm.begin(); originatorCache.put(key, "value"); final EmbeddedTransaction tx = tm.getTransaction(); final boolean success = tx.runPrepare(); assert success; log.trace("About to commit transaction."); tx.runCommit(false); return null; }); // Allow the tx thread to send the commit to the owners Thread.sleep(2000); log.trace("Lock transfer happens here"); killCache(); log.trace("Allow the commit RPC to proceed"); controlledRpcManager.stopBlocking(); // Ensure the commit finished on the other node f.get(); log.tracef("Commit finished"); // read the data from the container, just to make sure all replicas are correctly set checkValue(key, "value"); assertNoLocksOrTxs(key, originatorCache); assertNoLocksOrTxs(key, otherCache); } private void assertNoLocksOrTxs(Object key, Cache<Object, String> cache) { assertEventuallyNotLocked(originatorCache, key); final TransactionTable transactionTable = TestingUtil.extractComponent(cache, TransactionTable.class); eventually(new Condition() { @Override public boolean isSatisfied() throws Exception { return transactionTable.getLocalTxCount() == 0 && transactionTable.getRemoteTxCount() == 0; } }); } private ControlledRpcManager installControlledRpcManager(Class<? extends VisitableCommand> commandClass) { ControlledRpcManager controlledRpcManager = new ControlledRpcManager( originatorCache.getAdvancedCache().getRpcManager()); controlledRpcManager.blockBefore(commandClass); TestingUtil.replaceComponent(originatorCache, RpcManager.class, controlledRpcManager, true); return controlledRpcManager; } private void killCache() { if (stopCacheOnly) { killedCache.stop(); } else { manager(KILLED_INDEX).stop(); } if (waitForStateTransfer) { TestingUtil.waitForNoRebalance(originatorCache, otherCache); } } private void checkValue(Object key, String value) { if (!waitForStateTransfer) { TestingUtil.waitForNoRebalance(originatorCache, otherCache); } log.tracef("Checking key: %s", key); InternalCacheEntry d0 = advancedCache(ORIGINATOR_INDEX).getDataContainer().get(key); InternalCacheEntry d1 = advancedCache(OTHER_INDEX).getDataContainer().get(key); assertEquals(d0.getValue(), value); assertEquals(d1.getValue(), value); } private void checkNewTransactionFails(Object key) throws NotSupportedException, SystemException, HeuristicMixedException, HeuristicRollbackException { EmbeddedTransactionManager otherTM = embeddedTm(OTHER_INDEX); otherTM.begin(); otherCache.put(key, "should fail"); try { otherTM.commit(); fail("RollbackException should have been thrown here."); } catch (RollbackException e) { //expected } } private EmbeddedTransactionManager embeddedTm(int cacheIndex) { return (EmbeddedTransactionManager) tm(cacheIndex); } }
39.258182
153
0.733235
3b3ac7b3826cd08ee968ffd654a859377850edfe
1,346
package nl.altindag.ssl.trustmanager; import javax.net.ssl.X509ExtendedTrustManager; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; /** * <strong>NOTE:</strong> * Please don't use this class directly as it is part of the internal API. Class name and methods can be changed any time. * * @author Hakan Altindag */ interface CombinableX509ExtendedTrustManager extends X509TrustManager { String CERTIFICATE_EXCEPTION_MESSAGE = "None of the TrustManagers trust this certificate chain"; List<X509ExtendedTrustManager> getTrustManagers(); default void checkTrusted(TrustManagerConsumer callBackConsumer) throws CertificateException { List<CertificateException> certificateExceptions = new ArrayList<>(); for (X509ExtendedTrustManager trustManager : getTrustManagers()) { try { callBackConsumer.checkTrusted(trustManager); return; } catch (CertificateException e) { certificateExceptions.add(e); } } CertificateException certificateException = new CertificateException(CERTIFICATE_EXCEPTION_MESSAGE); certificateExceptions.forEach(certificateException::addSuppressed); throw certificateException; } }
34.512821
122
0.731798
ede3ed4fe10903f430da2c8cd885c5998d169f77
4,276
package com.synectiks.procurement.business.service; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.synectiks.procurement.domain.Invoice; import com.synectiks.procurement.repository.DocumentRepository; import com.synectiks.procurement.repository.InvoiceActivityRepository; import com.synectiks.procurement.repository.InvoiceRepository; import com.synectiks.procurement.repository.QuotationRepository; import com.synectiks.procurement.web.rest.errors.DataNotFoundException; import com.synectiks.procurement.web.rest.errors.IdNotFoundException; import com.synectiks.procurement.web.rest.errors.NegativeIdException; @ActiveProfiles("Invoice service test") @RunWith(SpringRunner.class) @ExtendWith(MockitoExtension.class) @SpringBootTest public class InvoiceServiceTest { @InjectMocks InvoiceService invoiceService; @Autowired InvoiceService invoiceServiceAuto; @Mock InvoiceRepository invoiceRepository; @Mock InvoiceActivityRepository invoiceActivityRepository; @Mock private QuotationRepository quotationRepository; @Mock private DocumentRepository documentRepository; private ObjectMapper mapper = new ObjectMapper(); Invoice invoice = new Invoice(); @Test public void addInvoiceTest() { ObjectNode obj = mapper.createObjectNode(); obj.put("invoiceNo", "a"); obj.put("modeOfPayment", "b"); obj.put("txnRefNo", "c"); obj.put("chequeOrDdNo", "d"); obj.put("issuerBank", "e"); obj.put("status", "f"); obj.put("notes", "g"); obj.put("documentId", "1"); obj.put("quotationId", "1"); invoice = invoiceServiceAuto.addInvoice(obj); assertThat(invoice.getInvoiceNo()).isEqualTo("a"); assertThat(invoice.getModeOfPayment()).isEqualTo("b"); assertThat(invoice.getTxnRefNo()).isEqualTo("c"); assertThat(invoice.getChequeOrDdNo()).isEqualTo("d"); assertThat(invoice.getIssuerBank()).isEqualTo("e"); assertThat(invoice.getStatus()).isEqualTo("f"); assertThat(invoice.getNotes()).isEqualTo("g"); } @Test public void searchInvoiceTest() throws NegativeIdException { invoice.invoiceNo("a"); invoice.setModeOfPayment("b"); List<Invoice> list1 = new ArrayList<>(); list1.add(invoice); HashMap<String, String> map = new HashMap<String, String>(); map.put("id", null); Mockito.when(invoiceRepository.findAll(Sort.by(Direction.DESC, "id"))).thenReturn(list1); List<Invoice> list = invoiceService.searchinvoice(map); assertThat(list).hasSize(1); for (Invoice e : list) { assertThat(e.getInvoiceNo()).isEqualTo("a"); assertThat(e.getModeOfPayment()).isEqualTo("b"); } } @Test public void updateInvoiceTest() { ObjectNode obj = mapper.createObjectNode(); obj.put("id", "1"); obj.put("invoiceNo", "aa"); obj.put("modeOfPayment", "bb"); invoice.setId(1L); invoice.setInvoiceNo("a"); invoice.setModeOfPayment("b"); Optional<Invoice> invoice2 = Optional.of(invoice); Mockito.when(invoiceRepository.findById(1L)).thenReturn(invoice2); Invoice invoice3 = new Invoice(); invoice3.setId(1L); invoice3.setInvoiceNo("aa"); invoice3.setModeOfPayment("bb"); Mockito.when(invoiceRepository.save(invoice)).thenReturn(invoice3); Invoice invoice4; try { invoice4 = invoiceService.updateinvoice(obj); assertThat(invoice4.getInvoiceNo()).isEqualTo("aa"); assertThat(invoice4.getModeOfPayment()).isEqualTo("bb"); } catch (NegativeIdException | IdNotFoundException | DataNotFoundException e) { e.printStackTrace(); } } }
28.697987
91
0.766137
b2c35f71119a6ab6fb27f7d4d366a77d66db6722
3,411
package net.oschina.ecust.team.fragment; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import net.oschina.ecust.R; import net.oschina.ecust.api.remote.OSChinaTeamApi; import net.oschina.ecust.base.BaseListFragment; import net.oschina.ecust.base.ListBaseAdapter; import net.oschina.ecust.team.adapter.TeamProjectMemberAdapter; import net.oschina.ecust.team.bean.Team; import net.oschina.ecust.team.bean.TeamMember; import net.oschina.ecust.team.bean.TeamMemberList; import net.oschina.ecust.team.bean.TeamProject; import net.oschina.ecust.team.ui.TeamMainActivity; import net.oschina.ecust.ui.empty.EmptyLayout; import net.oschina.ecust.util.UIHelper; import net.oschina.ecust.util.XmlUtils; import java.io.InputStream; import java.io.Serializable; import java.util.List; /** * TeamProjectFragment.java * * @author 火蚁(http://my.oschina.net/u/253900) * @data 2015-2-28 下午4:08:58 */ public class TeamProjectMemberFragment extends BaseListFragment<TeamMember> { private Team mTeam; private int mTeamId; private TeamProject mTeamProject; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); if (bundle != null) { mTeam = (Team) bundle .getSerializable(TeamMainActivity.BUNDLE_KEY_TEAM); mTeamProject = (TeamProject) bundle.getSerializable(TeamMainActivity.BUNDLE_KEY_PROJECT); mTeamId = mTeam.getId(); } } @Override protected TeamProjectMemberAdapter getListAdapter() { // TODO Auto-generated method stub return new TeamProjectMemberAdapter(); } @Override protected String getCacheKeyPrefix() { return "team_project_member_list_" + mTeamId + "_" + mTeamProject.getGit().getId(); } @Override protected TeamMemberList parseList(InputStream is) throws Exception { TeamMemberList list = XmlUtils.toBean( TeamMemberList.class, is); return list; } @Override protected TeamMemberList readList(Serializable seri) { return ((TeamMemberList) seri); } @Override protected void sendRequestData() { // TODO Auto-generated method stub OSChinaTeamApi.getTeamProjectMemberList(mTeamId, mTeamProject, mHandler, getContext()); } @Override protected void executeOnLoadDataSuccess(List<TeamMember> data) { // TODO Auto-generated method stub super.executeOnLoadDataSuccess(data); if (mAdapter.getData().isEmpty()) { setNoProjectMember(); } mAdapter.setState(ListBaseAdapter.STATE_NO_MORE); } private void setNoProjectMember() { mErrorLayout.setErrorType(EmptyLayout.NODATA); mErrorLayout.setErrorImag(R.mipmap.page_icon_empty); String str = getResources().getString( R.string.team_empty_project_member); mErrorLayout.setErrorMessage(str); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub TeamMember teamMember = mAdapter.getItem(position); if (teamMember != null) { UIHelper.showTeamMemberInfo(getActivity(), mTeamId, teamMember); } } }
30.455357
101
0.688068
2543bb64a55b151ecaf7ca05aa178cba0c53e0d6
1,404
package io.dropwizard.metrics.jdbi; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.TimingCollector; import io.dropwizard.metrics.jdbi.strategies.SmartNameStrategy; import io.dropwizard.metrics.jdbi.strategies.StatementNameStrategy; import io.dropwizard.metrics.MetricRegistry; import io.dropwizard.metrics.Timer; import java.util.concurrent.TimeUnit; /** * A {@link TimingCollector} implementation for JDBI which uses the SQL objects' class names and * method names for millisecond-precision timers. */ public class InstrumentedTimingCollector implements TimingCollector { private final MetricRegistry registry; private final StatementNameStrategy statementNameStrategy; public InstrumentedTimingCollector(MetricRegistry registry) { this(registry, new SmartNameStrategy()); } public InstrumentedTimingCollector(MetricRegistry registry, StatementNameStrategy statementNameStrategy) { this.registry = registry; this.statementNameStrategy = statementNameStrategy; } @Override public void collect(long elapsedTime, StatementContext ctx) { final Timer timer = getTimer(ctx); timer.update(elapsedTime, TimeUnit.NANOSECONDS); } private Timer getTimer(StatementContext ctx) { return registry.timer(statementNameStrategy.getStatementName(ctx)); } }
33.428571
96
0.754274
7465755fd8b09b4dec10dea7562bb9ad97e93b48
457
package it.unibz.inf.ontop.exception; /** * Thrown when loading the OBDA specification * * To be specialized * */ public class OBDASpecificationException extends Exception { protected OBDASpecificationException(String message) { super(message); } protected OBDASpecificationException(Exception e) { super(e); } protected OBDASpecificationException(String prefix, Exception e) { super(prefix, e); } }
19.869565
70
0.691466
ee8bb795b0459fea03c28507cbf967b057d793ff
2,217
/* * Original author: Daniel Jaschob <djaschob .at. uw.edu> * * Copyright 2018 University of Washington - Seattle, WA * * 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.yeastrc.limelight.limelight_importer.dto; import org.yeastrc.limelight.limelight_importer.constants.DatabaseAutoIncIdFieldForRecordNotInsertedYetConstants; /** * table protein_sequence_tbl * * equals(...) based on sequence */ public class ProteinSequenceDTO { private int id = DatabaseAutoIncIdFieldForRecordNotInsertedYetConstants.DB_AUTO_INC_FIELD_INITIAL_VALUE_FOR_NOT_INSERTED_YET; private String sequence; /** * Constructor */ public ProteinSequenceDTO() { } /** * Constructor * * @param sequence */ public ProteinSequenceDTO( String sequence ) { this.sequence = sequence; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((sequence == null) ? 0 : sequence.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProteinSequenceDTO other = (ProteinSequenceDTO) obj; if (sequence == null) { if (other.sequence != null) return false; } else if (!sequence.equals(other.sequence)) return false; return true; } @Override public String toString() { return "ProteinSequenceDTO [id=" + id + ", sequence=" + sequence + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSequence() { return sequence; } public void setSequence(String sequence) { this.sequence = sequence; } }
23.83871
126
0.7023
90dd5dc0e9f8587006f83789aaacd794130f2274
8,261
/* * Copyright (C) 2014 Indeed 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.indeed.imhotep; import com.google.common.base.Charsets; import com.indeed.util.core.io.Closeables2; import com.indeed.imhotep.api.RawFTGSIterator; import org.apache.log4j.Logger; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.CharsetDecoder; public class InputStreamFTGSIterator implements RawFTGSIterator { private static final Logger log = Logger.getLogger(RawFTGSIterator.class); private final byte[] buffer = new byte[32768]; private int bufferPtr = 0; private int bufferLen = 0; private byte readByte() throws IOException { if (bufferPtr == bufferLen) { refillBuffer(); } return buffer[bufferPtr++]; } private void readBytes(byte[] b, int off, int len) throws IOException { while (len > 0) { if (bufferPtr == bufferLen) { refillBuffer(); } final int toCopy = Math.min(len, bufferLen - bufferPtr); System.arraycopy(buffer, bufferPtr, b, off, toCopy); bufferPtr += toCopy; off += toCopy; len -= toCopy; } } private void refillBuffer() throws IOException { bufferLen = in.read(buffer); if (bufferLen == -1) { throw new IOException("Unexpected end of stream"); } bufferPtr = 0; } private int readVInt() throws IOException { int ret = 0; int shift = 0; while (true) { final byte val = readByte(); ret += (val&0x7F)<<shift; if (val >= 0) break; shift += 7; } return ret; } private long readVLong(byte firstByte) throws IOException { long ret = 0; int shift = 0; byte val = firstByte; while (true) { ret += (val&0x7FL)<<shift; if (val >= 0) break; shift += 7; val = readByte(); } return ret; } private long readSVLong() throws IOException { final long ret = readVLong(readByte()); return (ret >>> 1) ^ -(ret & 1); } private int iteratorStatus = 1; // 0 = end, 1 = reading fields, 2 = reading terms, 3 = reading groups private final InputStream in; public InputStreamFTGSIterator(InputStream in, int numStats) { this.in = in; this.statsBuf = new long[numStats]; } private String fieldName; private boolean fieldIsIntType; private long termDocFreq; private long intTermVal; private String stringTermVal; // needed to receive byte[] deltas over inputstream private byte[] currentTermBytes = new byte[16]; private ByteBuffer byteBuffer = ByteBuffer.wrap(currentTermBytes); private int currentTermLength; private int groupId = -1; private final long[] statsBuf; private final CharsetDecoder decoder = Charsets.UTF_8.newDecoder(); @Override public boolean nextField() { if (iteratorStatus < 1) return false; while (nextTerm()) { // skip until end of current field reached.... } // try to read next field from input stream... try { internalNextField(); } catch (IOException e) { iteratorStatus = -1; throw new RuntimeException(e); } return iteratorStatus == 2; } private void internalNextField() throws IOException { final int fieldType = readByte() & 0xFF; if (fieldType == 0) { iteratorStatus = 0; return; // normal end of stream condition } fieldIsIntType = fieldType == 1; final int fieldNameLength = readVInt(); final byte[] fieldNameBytes = new byte[fieldNameLength]; readBytes(fieldNameBytes, 0, fieldNameBytes.length); fieldName = new String(fieldNameBytes, Charsets.UTF_8); intTermVal = -1; stringTermVal = null; currentTermLength = 0; groupId = -1; iteratorStatus = 2; } @Override public final String fieldName() { return fieldName; } @Override public final boolean fieldIsIntType() { return fieldIsIntType; } @Override public final boolean nextTerm() { if (iteratorStatus < 2) return false; while (nextGroup()) { // skip until end of current term } try { internalNextTerm(); } catch (IOException e) { iteratorStatus = -1; throw new RuntimeException(e); } return iteratorStatus == 3; } private void internalNextTerm() throws IOException { if (fieldIsIntType) { final byte firstByte = readByte(); if (firstByte == 0) { iteratorStatus = 1; return; } intTermVal += readVLong(firstByte); } else { final int removeLengthPlusOne = readVInt(); final int addLength = readVInt(); if (removeLengthPlusOne == 0 && addLength == 0) { iteratorStatus = 1; return; } final int removeLength = removeLengthPlusOne - 1; final int newLength = currentTermLength - removeLength + addLength; if (currentTermBytes.length < newLength) { final byte[] temp = new byte[Math.max(currentTermBytes.length*2, newLength)]; System.arraycopy(currentTermBytes, 0, temp, 0, currentTermLength); currentTermBytes = temp; byteBuffer = ByteBuffer.wrap(currentTermBytes); } readBytes(currentTermBytes, currentTermLength - removeLength, addLength); currentTermLength = newLength; stringTermVal = null; } termDocFreq = readSVLong(); groupId = -1; iteratorStatus = 3; } @Override public final long termDocFreq() { return termDocFreq; } @Override public final long termIntVal() { return intTermVal; } @Override public final String termStringVal() { if (stringTermVal == null) { try { stringTermVal = decoder.decode((ByteBuffer)byteBuffer.position(0).limit(currentTermLength)).toString(); } catch (CharacterCodingException e) { throw new RuntimeException(e); } } return stringTermVal; } @Override public final byte[] termStringBytes() { return currentTermBytes; } @Override public final int termStringLength() { return currentTermLength; } @Override public final boolean nextGroup() { if (iteratorStatus < 3) { return false; } try { final int grpDelta = readVInt(); if (grpDelta == 0) { iteratorStatus = 2; } else { groupId += grpDelta; for (int i = 0; i < statsBuf.length; i++) { statsBuf[i] = readSVLong(); } } } catch (IOException e) { iteratorStatus = -1; throw new RuntimeException(e); } return iteratorStatus == 3; } @Override public final int group() { return groupId; } @Override public final void groupStats(long[] stats) { System.arraycopy(statsBuf, 0, stats, 0, statsBuf.length); } @Override public void close() { Closeables2.closeQuietly(in, log); } }
29.190813
119
0.579712
e8f13fdbedd66e8d697ac5f6f1ffc0cc8d435d3d
1,218
package net.gitsaibot.af; import net.gitsaibot.af.AfProvider.AfWidgets; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.ContentUris; import android.content.Context; import android.content.Intent; public class AfWidget extends AppWidgetProvider { @Override public void onDeleted(Context context, int[] appWidgetIds) { for (int appWidgetId : appWidgetIds) { Intent updateIntent = new Intent( AfService.ACTION_DELETE_WIDGET, ContentUris.withAppendedId(AfWidgets.CONTENT_URI, appWidgetId), context, AfService.class); AfService.enqueueWork(context, updateIntent); } } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { if (appWidgetIds == null) { appWidgetIds = appWidgetManager.getAppWidgetIds( new ComponentName(context, AfWidget.class)); } for (int appWidgetId : appWidgetIds) { Intent updateIntent = new Intent( AfService.ACTION_UPDATE_WIDGET, ContentUris.withAppendedId(AfWidgets.CONTENT_URI, appWidgetId), context, AfService.class); AfService.enqueueWork(context, updateIntent); } } }
29
73
0.770936
4a73e331ee37727903c453f9f9fd8eacfc639f34
400
package com.teamwill.rmkpro.service.mapper; import com.teamwill.rmkpro.domain.Vehicle; import com.teamwill.rmkpro.service.dto.VehicleDTO; import org.mapstruct.Mapper; /** * Mapper for the entity {@link Vehicle} and its DTO called {@link VehicleDTO}. */ @Mapper public interface VehicleMapper { VehicleDTO mapEntityToDto(Vehicle entity); Vehicle mapDtoToEntity(VehicleDTO entityDto); }
22.222222
79
0.7725
83bfc9fd211149b76f5ddd90577ad91c0b71f12c
952
package org.mlaptev.otus; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class SubListTest { private MyArrayList<Integer> myArrayList; @BeforeEach void setup() { myArrayList = new MyArrayList<>(); } @Test void subListThrowsIndexOutOfBoundsIfFromIndexIsNegative() { // Arrange & Act & Assert assertThrows(IndexOutOfBoundsException.class, () -> myArrayList.subList(-1, 1)); } @Test void subListThrowsIndexOutOfBoundsIfToIndexIsGreaterThanSize() { // Arrange & Act myArrayList.add(0); myArrayList.add(1); // Assert assertThrows(IndexOutOfBoundsException.class, () -> myArrayList.subList(1, 3)); } @Test void subListThrowsIndexOutOfBoundsIfToIndexIsGreaterThanFromIndex() { // Arrange & Act & Assert assertThrows(IndexOutOfBoundsException.class, () -> myArrayList.subList(2, 1)); } }
24.410256
84
0.72479
bb976e6f879d506ad7c7692f5ec83d916251fa3c
8,768
package org.codehaus.groovy.tools; import org.codehaus.groovy.classgen.BytecodeHelper; import org.codehaus.groovy.reflection.CachedClass; import org.codehaus.groovy.reflection.CachedMethod; import org.codehaus.groovy.reflection.ReflectionCache; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import java.io.FileOutputStream; import java.io.IOException; public class DgmConverter implements Opcodes{ private static BytecodeHelper helper; public static void main(String[] args) throws IOException, ClassNotFoundException { final CachedClass dgm = ReflectionCache.getCachedClass(DefaultGroovyMethods.class); final CachedMethod[] cachedMethods = dgm.getMethods(); for (int i = 0, cur = 0; i < cachedMethods.length; i++) { CachedMethod method = cachedMethods[i]; if (!method.isStatic() || !method.isPublic()) continue; if (method.getParameterTypes().length == 0) continue; ClassWriter cw = new ClassWriter(true); final String className = "org/codehaus/groovy/runtime/dgm$" + cur; cw.visit(V1_3,ACC_PUBLIC, className,null,"org/codehaus/groovy/reflection/GeneratedMetaMethod", null); MethodVisitor mv; mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "org/codehaus/groovy/reflection/GeneratedMetaMethod", "<init>", "()V"); mv.visitInsn(RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); final Class returnType = method.getReturnType(); final String methodDescriptor = BytecodeHelper.getMethodDescriptor(returnType, method.getNativeParameterTypes()); mv = cw.visitMethod(ACC_PUBLIC, "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", null, null); helper = new BytecodeHelper(mv); mv.visitCode(); mv.visitVarInsn(ALOAD,1); helper.doCast(method.getParameterTypes()[0].getTheClass()); loadParameters(method,2,mv); mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/DefaultGroovyMethods", method.getName(), methodDescriptor); helper.box(returnType); if (method.getReturnType() == void.class) { mv.visitInsn(ACONST_NULL); } mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "doMethodInvoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", null, null); helper = new BytecodeHelper(mv); mv.visitCode(); if (method.getParamsCount() == 2 && method.getParameterTypes()[0].isNumber && method.getParameterTypes()[1].isNumber) { mv.visitVarInsn(ALOAD,1); helper.doCast(method.getParameterTypes()[0].getTheClass()); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKEVIRTUAL, className, "getParameterTypes", "()[Lorg/codehaus/groovy/reflection/CachedClass;"); mv.visitInsn(ICONST_0); mv.visitInsn(AALOAD); mv.visitVarInsn(ALOAD, 2); mv.visitInsn(ICONST_0); mv.visitInsn(AALOAD); mv.visitMethodInsn(INVOKEVIRTUAL, "org/codehaus/groovy/reflection/CachedClass", "coerceArgument", "(Ljava/lang/Object;)Ljava/lang/Object;"); // cast argument to parameter class, inclusive unboxing // for methods with primitive types Class type = method.getParameterTypes()[1].getTheClass(); if (type.isPrimitive()) { helper.unbox(type); } else { helper.doCast(type); } } else { mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEVIRTUAL, className, "coerceArgumentsToClasses", "([Ljava/lang/Object;)[Ljava/lang/Object;"); mv.visitVarInsn(ASTORE, 2); mv.visitVarInsn(ALOAD,1); helper.doCast(method.getParameterTypes()[0].getTheClass()); loadParameters(method,2,mv); } mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/DefaultGroovyMethods", method.getName(), methodDescriptor); helper.box(returnType); if (method.getReturnType() == void.class) { mv.visitInsn(ACONST_NULL); } mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); if (method.getParamsCount() == 2 && method.getParameterTypes()[0].isNumber && method.getParameterTypes()[1].isNumber) { // 1 param meta method mv = cw.visitMethod(ACC_PUBLIC, "isValidMethod", "([Ljava/lang/Class;)Z", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 1); Label l0 = new Label(); mv.visitJumpInsn(IFNULL, l0); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKEVIRTUAL, className, "getParameterTypes", "()[Lorg/codehaus/groovy/reflection/CachedClass;"); mv.visitInsn(ICONST_0); mv.visitInsn(AALOAD); mv.visitVarInsn(ALOAD, 1); mv.visitInsn(ICONST_0); mv.visitInsn(AALOAD); mv.visitMethodInsn(INVOKEVIRTUAL, "org/codehaus/groovy/reflection/CachedClass", "isAssignableFrom", "(Ljava/lang/Class;)Z"); Label l1 = new Label(); mv.visitJumpInsn(IFEQ, l1); mv.visitLabel(l0); mv.visitInsn(ICONST_1); Label l2 = new Label(); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_0); mv.visitLabel(l2); mv.visitInsn(IRETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } mv = cw.visitMethod(ACC_PUBLIC, "$markerMethod$" + method.getName(), methodDescriptor, null, null); mv.visitCode(); if (returnType == Void.TYPE) mv.visitInsn(RETURN); else { if (returnType.isPrimitive()) { if (returnType == float.class) { mv.visitInsn(FCONST_0); mv.visitInsn(FRETURN); } else if (returnType == double.class) { mv.visitInsn(DCONST_0); mv.visitInsn(DRETURN); } else if (returnType == long.class) { mv.visitInsn(LCONST_0); mv.visitInsn(LRETURN); } else if (returnType == float.class) { mv.visitInsn(FCONST_0); mv.visitInsn(FRETURN); } else { mv.visitInsn(ICONST_0); mv.visitInsn(IRETURN); } } else { mv.visitInsn(ACONST_NULL); mv.visitInsn(ARETURN); } } mv.visitMaxs(0, 0); mv.visitEnd(); cw.visitEnd(); final byte[] bytes = cw.toByteArray(); final FileOutputStream fileOutputStream = new FileOutputStream("target/classes/" + className + ".class"); fileOutputStream.write(bytes); fileOutputStream.flush(); fileOutputStream.close(); cur++; } } protected static void loadParameters(CachedMethod method, int argumentIndex, MethodVisitor mv) { CachedClass[] parameters = method.getParameterTypes(); int size = parameters.length-1; for (int i = 0; i < size; i++) { // unpack argument from Object[] mv.visitVarInsn(ALOAD, argumentIndex); helper.pushConstant(i); mv.visitInsn(AALOAD); // cast argument to parameter class, inclusive unboxing // for methods with primitive types Class type = parameters[i+1].getTheClass(); if (type.isPrimitive()) { helper.unbox(type); } else { helper.doCast(type); } } } }
43.192118
156
0.552806
31083521ed8804a291c67c4c23dcf4757de31fae
2,078
package com.github.tusharepro.core.entity; import lombok.Data; import com.github.tusharepro.core.bean.FundBasic; import javax.persistence.*; import java.time.LocalDate; /** * 公募基金列表 * https://tushare.pro/document/2?doc_id=19 */ @Data @Entity @Table(name = "fund_basic") public class FundBasicEntity implements FundBasic { @Id @Column(name = "ts_code") protected String tsCode; // 基金代码 @Column(name = "name") protected String name; // 简称 @Column(name = "management") protected String management; // 管理人 @Column(name = "custodian") protected String custodian; // 托管人 @Column(name = "fund_type") protected String fundType; // 投资类型 @Column(name = "found_date") protected LocalDate foundDate; // 成立日期 @Column(name = "due_date") protected LocalDate dueDate; // 到期日期 @Column(name = "list_date") protected LocalDate listDate; // 上市时间 @Column(name = "issue_date") protected LocalDate issueDate; // 发行日期 @Column(name = "delist_date") protected LocalDate delistDate; // 退市日期 @Column(name = "issue_amount") protected Double issueAmount; // 发行份额(亿) @Column(name = "m_fee") protected Double mFee; // 管理费 @Column(name = "c_fee") protected Double cFee; // 托管费 @Column(name = "duration_year") protected Double durationYear; // 存续期 @Column(name = "p_value") protected Double pValue; // 面值 @Column(name = "min_amount") protected Double minAmount; // 起点金额(万元) @Column(name = "exp_return") protected Double expReturn; // 预期收益率 @Column(name = "benchmark") protected String benchmark; // 业绩比较基准 @Column(name = "status") protected String status; // 存续状态D摘牌 I发行 L已上市 @Column(name = "invest_type") protected String investType; // 投资风格 @Column(name = "type") protected String type; // 基金类型 @Column(name = "trustee") protected String trustee; // 受托人 @Column(name = "purc_startdate") protected LocalDate purcStartdate; // 日常申购起始日 @Column(name = "redm_startdate") protected LocalDate redmStartdate; // 日常赎回起始日 @Column(name = "market") protected String market; // E场内O场外 }
46.177778
83
0.691049
bbd4eaef85f245ac0f48455b00d60c28a181ff41
3,939
package com.google.speech.tools.voxetta.services; import com.google.appengine.api.datastore.DatastoreFailureException; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.gson.Gson; import com.google.speech.tools.voxetta.data.PromptBuilder; import com.google.speech.tools.voxetta.data.StatusResponse; import java.util.LinkedList; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class DatastorePromptServiceTest extends Mockito { private LocalServiceTestHelper serviceHelper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()); private DatastorePromptService service; private DatastoreService datastoreService; private HttpServletRequest request; private PreparedQuery preparedQuery; private Gson gson = new Gson(); @Before public void setUpServiceHelper() { serviceHelper.setUp(); } @After public void tearDownServiceHelper() { serviceHelper.tearDown(); } @Before public void setUpMocksAndServletInstance() { datastoreService = Mockito.mock(DatastoreService.class); service = new DatastorePromptService(); service.setDatastoreService(datastoreService); request = Mockito.mock(HttpServletRequest.class); preparedQuery = Mockito.mock(PreparedQuery.class); } @Test public void getOnePrompt_DatastorePromptRetrieval_ReturnsPrompt() { // Mock entity Entity mockEntity = new Entity(KeyFactory.createKey("Prompt", 7823648)); mockEntity.setProperty("type", "text"); mockEntity.setProperty("body", "dummy prompt"); String mockEntityAsPromptJson = gson.toJson(new PromptBuilder().buildFromEntity(mockEntity)); // Mock entityList List<Entity> entityList = new LinkedList<Entity>(); entityList.add(mockEntity); // Prepare mocked responses when(datastoreService.prepare(any(Query.class))).thenReturn(preparedQuery); when(preparedQuery.asList(any(FetchOptions.class))).thenReturn(entityList); // Assert equal String retrievedPrompt = service.getOnePrompt(); Assert.assertEquals(mockEntityAsPromptJson, retrievedPrompt); } @Test public void getOnePrompt_DatastorePromptRetrieval_ReturnsEmptyPrompt() { // Mock empty entityList List<Entity> entityList = new LinkedList<Entity>(); // Prepare mocked responses when(datastoreService.prepare(any(Query.class))).thenReturn(preparedQuery); when(preparedQuery.asList(any(FetchOptions.class))).thenReturn(entityList); // Assert empty JSON is returned String retrievedPrompt = service.getOnePrompt(); Assert.assertEquals(gson.toJson(new Object()), retrievedPrompt); } @Test public void savePrompt_PromptSavingSuccess_ReturnsTrue() { StatusResponse savePromptResponse = service.savePrompt("text", "mock prompt body"); Assert.assertTrue(savePromptResponse.getSuccess()); } @Test public void savePrompt_PromptSavingFailure_ReturnsFalse() { when(datastoreService.put(any(Entity.class))).thenThrow(new DatastoreFailureException("Failure")); StatusResponse savePromptResponse = service.savePrompt("text", "mock prompt body"); Assert.assertFalse(savePromptResponse.getSuccess()); } }
36.137615
106
0.741813
0974d4f1aa8744c5d84657fdad197f59fe73f4a9
5,106
/* * Copyright 2019 Johnny850807 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2019 Johnny850807 * * 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 tw.waterball.demo; /** * Not yet implemented, Instagram4J doesn't support story's url handling. * The code below uses the contributed version : https://github.com/jvogit/instagram4j * Which made story crawling work. * @author johnny850807 (Waterball) */ public class InstagramStoryCrawler { // private final String USERNAME; // private final String DIRNAME_STORIES_REPOSITORY; // private Instagram4j instagram; // private InstagramUser user; // private int currentBatchNewStories = 0; // // public InstagramStoryCrawler(String username) { // this.USERNAME = username; // this.DIRNAME_STORIES_REPOSITORY = USERNAME + "/stories"; // } // // public void start() throws IOException, InterruptedException { // System.out.println("Crawling " + USERNAME + " ..."); // instagram = login(); // user = getUser(USERNAME); // createUserDirectoryIfNotExists(); // // while(true) { // currentBatchNewStories = 0; // getStoriesFromUser().stream() // .map(this::getUrlFromStory) // .filter(Objects::nonNull) // filter out invalid URL's // .forEach(this::downloadMediaFromURL); // // System.out.println("Got " + currentBatchNewStories + " new stories in this batch."); // System.out.println("Sleeping five minutes ... "); // TimeUnit.MINUTES.sleep(5); // } // } // // private void createUserDirectoryIfNotExists() throws IOException { // if (Files.notExists(Paths.get(USERNAME))) // { // Files.createDirectory(Paths.get(USERNAME)); // Files.createDirectory(Paths.get(DIRNAME_STORIES_REPOSITORY)); // } // } // // // private Instagram4j login() throws IOException { // String username = "dailymatchman"; // String password = InstagramProperties.password("dailymatchman"); // // Instagram4j instagram = Instagram4j.builder().username(username).password(password).build(); // instagram.setup(); // instagram.login(); // return instagram; // } // // private InstagramUser getUser(String username) throws IOException { // return instagram.sendRequest(new InstagramSearchUsernameRequest(username)).getUser(); // } // // private List<InstagramStoryItem> getStoriesFromUser() throws IOException { // InstagramUserReelMediaFeedResult result = instagram.sendRequest( // new InstagramGetUserReelMediaFeedRequest(user.getPK())); // return result.getItems(); // } // // // private URL getUrlFromStory(InstagramStoryItem item) { // try { // switch (item.media_type) { // case InstagramItem.PHOTO: // return new URL(item.image_versions2.candidates.get(0).getUrl()); // case InstagramItem.VIDEO: // return new URL(item.video_versions.get(0).getUrl()); // } // } catch (MalformedURLException err) { // return null; // } // return null; // } // // private void downloadMediaFromURL(URL url) { // String fileName = FilenameUtils.getName(url.getPath()); // File targetFile = Paths.get(DIRNAME_STORIES_REPOSITORY, fileName).toFile(); // if (!targetFile.exists()) // { // try { // System.out.println("Download media into " + targetFile + " ..."); // FileUtils.copyURLToFile(url, targetFile, 60000, 60000); // currentBatchNewStories ++; // } catch (IOException err) { // err.printStackTrace(); // } // } // } // // public static void main(String[] args) throws InterruptedException, IOException { // new InstagramStoryCrawler("c.seulcoin").start(); // } }
37.544118
102
0.626714
e8264f6ac6e56ff0fa1f5d3e9cac3472712d1dbc
4,443
//Author: Timothy van der Graaff package views; import java.util.ArrayList; import utilities.Find_and_replace; public class Show_For_Sale_Items { //global variables public static ArrayList<String> for_sale_categories = new ArrayList<>(); public static ArrayList<ArrayList<String>> for_sale_items = new ArrayList<>(); public static int page_number_count; public static String show_for_sale_categories() { String output = ""; ArrayList<String> find = new ArrayList<>(); ArrayList<String> replace = new ArrayList<>(); find.add("<script"); find.add("<style"); find.add("\""); find.add("'"); find.add("<br />"); find.add("<br>"); find.add("<div>"); find.add("</div>"); replace.add("&lt;script"); replace.add("&lt;style"); replace.add("&quot;"); replace.add("&apos;"); replace.add(" "); replace.add(""); replace.add(""); replace.add(""); output += "["; for (int i = 0; i < for_sale_categories.size(); i++) { output += "{\"category\": \"" + Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_categories.get(i)).replace("<", "&lt;").replace(">", "&gt;")) + "\"}, "; } output += "{}]"; output = output.replace(", {}", ""); return output; } public static String show_for_sale_items() { String output = ""; ArrayList<String> find = new ArrayList<>(); ArrayList<String> replace = new ArrayList<>(); find.add("<script"); find.add("<style"); find.add("\""); find.add("'"); find.add("<br />"); find.add("<br>"); find.add("<div>"); find.add("</div>"); replace.add("&lt;script"); replace.add("&lt;style"); replace.add("&quot;"); replace.add("&apos;"); replace.add(" "); replace.add(""); replace.add(""); replace.add(""); output += "["; for (int i = 0; i < for_sale_items.get(0).size(); i++) { output += "{\"row_id\": \"" + Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_items.get(0).get(i)).replace("<", "&lt;").replace(">", "&gt;")) + "\", \"item\": \"" + Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_items.get(1).get(i)).replace("<", "&lt;").replace(">", "&gt;")) + "\", \"thumbnail\": \"" + Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_items.get(2).get(i)).replace("<", "&lt;").replace(">", "&gt;")) + "\", \"item_category\": \"" + Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_items.get(3).get(i)).replace("<", "&lt;").replace(">", "&gt;")) + "\", \"description\": \"" + Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_items.get(4).get(i)).replace("<", "&lt;").replace(">", "&gt;")) + "\", \"price\": \"" + Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_items.get(5).get(i)).replace("<", "&lt;").replace(">", "&gt;")) + "\", \"inventory\": \"" + Find_and_replace.find_and_replace(find, replace, String.valueOf(for_sale_items.get(6).get(i)).replace("<", "&lt;").replace(">", "&gt;")) + "\"}, "; } output += "{}]"; output = output.replace(", {}", ""); return output; } public static String show_page_numbers() { String output = ""; output += "["; for (int i = 0; i < page_number_count; i++) { output += "{\"page_number\": \"" + (i + 1) + "\"}, "; } output += "{}]"; output = output.replace(", {}", ""); return output; } }
35.544
159
0.453297
5938d070be22e55492dc67a84a4f98673752cd4d
7,579
package com.simon.core.animationtools.animator; import android.animation.Keyframe; import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.util.Log; import android.util.Property; import android.view.animation.Animation; import android.view.animation.Interpolator; import com.simon.core.animationtools.animator.interpolator.KeyFrameInterpolator; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * * Created by simon on 17-6-7. */ public abstract class AnimatorBuilder { private static final String TAG = "AnimatorBuilder"; private Object target; private Interpolator interpolator; private int repeatCount = Animation.INFINITE; private long duration = 2000; private int startFrame = 0; private Map<String, FrameData> fds = new HashMap<>(); class FrameData<T> { FrameData(float[] fractions, Property property, T[] values) { this.fractions = fractions; this.property = property; this.values = values; } float[] fractions; Property property; T[] values; } private class IntFrameData extends FrameData<Integer> { IntFrameData(float[] fractions, Property property, Integer[] values) { super(fractions, property, values); } } private class FloatFrameData extends FrameData<Float> { FloatFrameData(float[] fractions, Property property, Float[] values) { super(fractions, property, values); } } public AnimatorBuilder(Object target) { this.target = target; } protected abstract Property getScaleProperty(); public AnimatorBuilder scale(float fractions[], Float... scale) { holder(fractions, getScaleProperty(), scale); return this; } protected abstract Property getAlphaProperty(); public AnimatorBuilder alpha(float fractions[], Float... alpha) { holder(fractions, getAlphaProperty(), alpha); return this; } protected abstract Property getScaleXProperty(); @SuppressWarnings("unused") public AnimatorBuilder scaleX(float fractions[], Float... scaleX) { holder(fractions, getScaleXProperty(), scaleX); return this; } protected abstract Property getScaleYProperty(); public AnimatorBuilder scaleY(float fractions[], Float... scaleY) { holder(fractions, getScaleYProperty(), scaleY); return this; } protected abstract Property getRotateXProperty(); public AnimatorBuilder rotateX(float fractions[], Float... rotateX) { holder(fractions, getRotateXProperty(), rotateX); return this; } protected abstract Property getRotateYProperty(); public AnimatorBuilder rotateY(float fractions[], Float... rotateY) { holder(fractions, getRotateYProperty(), rotateY); return this; } protected abstract Property getTranslateXProperty(); @SuppressWarnings("unused") public AnimatorBuilder translateX(float fractions[], Float... translateX) { holder(fractions, getTranslateXProperty(), translateX); return this; } protected abstract Property getTranslateYProperty(); @SuppressWarnings("unused") public AnimatorBuilder translateY(float fractions[], Float... translateY) { holder(fractions, getTranslateYProperty(), translateY); return this; } protected abstract Property getRotateProperty(); public AnimatorBuilder rotate(float fractions[], Float... rotate) { holder(fractions, getRotateProperty(), rotate); return this; } protected abstract Property getTranslateXPercentageProperty(); public AnimatorBuilder translateXPercentage(float fractions[], Float... translateXPercentage) { holder(fractions, getTranslateXPercentageProperty(), translateXPercentage); return this; } protected abstract Property getTranslateYPercentageProperty(); public AnimatorBuilder translateYPercentage(float[] fractions, Float... translateYPercentage) { holder(fractions, getTranslateYPercentageProperty(), translateYPercentage); return this; } private void holder(float[] fractions, Property property, Float[] values) { ensurePair(fractions.length, values.length); fds.put(property.getName(), new FloatFrameData(fractions, property, values)); } private void holder(float[] fractions, Property property, Integer[] values) { ensurePair(fractions.length, values.length); fds.put(property.getName(), new IntFrameData(fractions, property, values)); } private void ensurePair(int fractionsLength, int valuesLength) { if (fractionsLength != valuesLength) { throw new IllegalStateException(String.format( Locale.getDefault(), "The fractions.length must equal values.length, " + "fraction.length[%d], values.length[%d]", fractionsLength, valuesLength)); } } public AnimatorBuilder interpolator(Interpolator interpolator) { this.interpolator = interpolator; return this; } public AnimatorBuilder easeInOut(float... fractions) { interpolator(KeyFrameInterpolator.easeInOut( fractions )); return this; } public AnimatorBuilder duration(long duration) { this.duration = duration; return this; } @SuppressWarnings("unused") public AnimatorBuilder repeatCount(int repeatCount) { this.repeatCount = repeatCount; return this; } public AnimatorBuilder startFrame(int startFrame) { if (startFrame < 0) { Log.w(TAG, "startFrame should always be non-negative"); startFrame = 0; } this.startFrame = startFrame; return this; } public ObjectAnimator build() { PropertyValuesHolder[] holders = new PropertyValuesHolder[fds.size()]; int i = 0; for (Map.Entry<String, FrameData> fd : fds.entrySet()) { FrameData data = fd.getValue(); Keyframe[] keyframes = new Keyframe[data.fractions.length]; float[] fractions = data.fractions; float startF = fractions[startFrame]; for (int j = startFrame; j < (startFrame + data.values.length); j++) { int key = j - startFrame; int vk = j % data.values.length; float fraction = fractions[vk] - startF; if (fraction < 0) { fraction = fractions[fractions.length - 1] + fraction; } if (data instanceof IntFrameData) { keyframes[key] = Keyframe.ofInt(fraction, (Integer) data.values[vk]); } else if (data instanceof FloatFrameData) { keyframes[key] = Keyframe.ofFloat(fraction, (Float) data.values[vk]); } else { keyframes[key] = Keyframe.ofObject(fraction, data.values[vk]); } } holders[i] = PropertyValuesHolder.ofKeyframe(data.property, keyframes); i++; } ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(target, holders); animator.setDuration(duration); animator.setRepeatCount(repeatCount); animator.setInterpolator(interpolator); return animator; } }
31.844538
99
0.643489
26e0af038698a4992716474de3b7cd6d1aa1ecac
1,670
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the repository root. /* * This file was automatically generated by com.microsoft.tfs.core.ws.generator.Generator * from the /complexType.vm template. */ package ms.tfs.versioncontrol.clientservices._03; import com.microsoft.tfs.core.ws.runtime.*; import com.microsoft.tfs.core.ws.runtime.serialization.*; import com.microsoft.tfs.core.ws.runtime.types.*; import com.microsoft.tfs.core.ws.runtime.util.*; import com.microsoft.tfs.core.ws.runtime.xml.*; import ms.tfs.versioncontrol.clientservices._03._BaseLocalVersionUpdate; import java.lang.String; import java.util.ArrayList; import java.util.List; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; /** * Automatically generated complex type class. */ public abstract class _BaseLocalVersionUpdate implements ElementSerializable, ElementDeserializable { // Attributes protected String tlocal; protected int lver; // No elements protected _BaseLocalVersionUpdate() { super(); } public String getTlocal() { return this.tlocal; } public void setTlocal(final String value) { this.tlocal = value; } public int getLver() { return this.lver; } public void setLver(final int value) { this.lver = value; } /* * Abstract do not contain serialization methods. Derived classes serialize the base * type's attributes and elements directly. */ }
24.202899
89
0.71497
79895aaaee23e0a6c6e27b7ca2d42f0cc26dc01a
484
package arcrow.contentium.blocks; import arcrow.contentium.core.utils.Utils; import arcrow.contentium.lib.Reference; import net.minecraft.block.BlockBush; import net.minecraft.creativetab.CreativeTabs; public class LilyValley extends BlockBush { public LilyValley() { this.setHardness(0F); this.setCreativeTab(CreativeTabs.tabDecorations); setBlockName(Utils.getUnlocalisedName("lily_valley")); this.setBlockTextureName(Reference.MOD_ID + ":flower/lily_valley"); } }
23.047619
69
0.799587
c19ec1447d3d039510e1ff4fbb88c83bd6d87f14
496
package com.ianprime0509.jsonrecipe.server.data; import org.apache.commons.math3.fraction.Fraction; import org.bson.Document; import org.springframework.core.convert.converter.Converter; /** A converter to read {@link Fraction} objects from a Mongo document. */ public class FractionReadConverter implements Converter<Document, Fraction> { @Override public Fraction convert(Document source) { return new Fraction(source.getInteger("numerator"), source.getInteger("denominator")); } }
35.428571
90
0.788306
03194c897e8c3751e88c0453578fb7e3b833be78
14,008
/** * AvaFileForm.java * * This file was auto-generated from WSDL * by the Apache Axis 1.2.1 Jun 14, 2005 (09:15:57 EDT) WSDL2Java emitter. */ package com.avalara.avatax.services.account; public class AvaFileForm implements java.io.Serializable { private int avaFileFormId; private java.lang.String formName; private java.lang.String returnName; private java.lang.String description; private java.util.Calendar effDate; private java.util.Calendar endDate; private java.lang.String region; private java.lang.String country; private int formType; private com.avalara.avatax.services.account.ArrayOfAvaFileFormGroup groups; public AvaFileForm() { } public AvaFileForm( int avaFileFormId, java.lang.String formName, java.lang.String returnName, java.lang.String description, java.util.Calendar effDate, java.util.Calendar endDate, java.lang.String region, java.lang.String country, int formType, com.avalara.avatax.services.account.ArrayOfAvaFileFormGroup groups) { this.avaFileFormId = avaFileFormId; this.formName = formName; this.returnName = returnName; this.description = description; this.effDate = effDate; this.endDate = endDate; this.region = region; this.country = country; this.formType = formType; this.groups = groups; } /** * Gets the avaFileFormId value for this AvaFileForm. * * @return avaFileFormId */ public int getAvaFileFormId() { return avaFileFormId; } /** * Sets the avaFileFormId value for this AvaFileForm. * * @param avaFileFormId */ public void setAvaFileFormId(int avaFileFormId) { this.avaFileFormId = avaFileFormId; } /** * Gets the formName value for this AvaFileForm. * * @return formName */ public java.lang.String getFormName() { return formName; } /** * Sets the formName value for this AvaFileForm. * * @param formName */ public void setFormName(java.lang.String formName) { this.formName = formName; } /** * Gets the returnName value for this AvaFileForm. * * @return returnName */ public java.lang.String getReturnName() { return returnName; } /** * Sets the returnName value for this AvaFileForm. * * @param returnName */ public void setReturnName(java.lang.String returnName) { this.returnName = returnName; } /** * Gets the description value for this AvaFileForm. * * @return description */ public java.lang.String getDescription() { return description; } /** * Sets the description value for this AvaFileForm. * * @param description */ public void setDescription(java.lang.String description) { this.description = description; } /** * Gets the effDate value for this AvaFileForm. * * @return effDate */ public java.util.Calendar getEffDate() { return effDate; } /** * Sets the effDate value for this AvaFileForm. * * @param effDate */ public void setEffDate(java.util.Calendar effDate) { this.effDate = effDate; } /** * Gets the endDate value for this AvaFileForm. * * @return endDate */ public java.util.Calendar getEndDate() { return endDate; } /** * Sets the endDate value for this AvaFileForm. * * @param endDate */ public void setEndDate(java.util.Calendar endDate) { this.endDate = endDate; } /** * Gets the region value for this AvaFileForm. * * @return region */ public java.lang.String getRegion() { return region; } /** * Sets the region value for this AvaFileForm. * * @param region */ public void setRegion(java.lang.String region) { this.region = region; } /** * Gets the country value for this AvaFileForm. * * @return country */ public java.lang.String getCountry() { return country; } /** * Sets the country value for this AvaFileForm. * * @param country */ public void setCountry(java.lang.String country) { this.country = country; } /** * Gets the formType value for this AvaFileForm. * * @return formType */ public int getFormType() { return formType; } /** * Sets the formType value for this AvaFileForm. * * @param formType */ public void setFormType(int formType) { this.formType = formType; } /** * Gets the groups value for this AvaFileForm. * * @return groups */ public com.avalara.avatax.services.account.ArrayOfAvaFileFormGroup getGroups() { return groups; } /** * Sets the groups value for this AvaFileForm. * * @param groups */ public void setGroups(com.avalara.avatax.services.account.ArrayOfAvaFileFormGroup groups) { this.groups = groups; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof AvaFileForm)) return false; AvaFileForm other = (AvaFileForm) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && this.avaFileFormId == other.getAvaFileFormId() && ((this.formName==null && other.getFormName()==null) || (this.formName!=null && this.formName.equals(other.getFormName()))) && ((this.returnName==null && other.getReturnName()==null) || (this.returnName!=null && this.returnName.equals(other.getReturnName()))) && ((this.description==null && other.getDescription()==null) || (this.description!=null && this.description.equals(other.getDescription()))) && ((this.effDate==null && other.getEffDate()==null) || (this.effDate!=null && this.effDate.equals(other.getEffDate()))) && ((this.endDate==null && other.getEndDate()==null) || (this.endDate!=null && this.endDate.equals(other.getEndDate()))) && ((this.region==null && other.getRegion()==null) || (this.region!=null && this.region.equals(other.getRegion()))) && ((this.country==null && other.getCountry()==null) || (this.country!=null && this.country.equals(other.getCountry()))) && this.formType == other.getFormType() && ((this.groups==null && other.getGroups()==null) || (this.groups!=null && this.groups.equals(other.getGroups()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; _hashCode += getAvaFileFormId(); if (getFormName() != null) { _hashCode += getFormName().hashCode(); } if (getReturnName() != null) { _hashCode += getReturnName().hashCode(); } if (getDescription() != null) { _hashCode += getDescription().hashCode(); } if (getEffDate() != null) { _hashCode += getEffDate().hashCode(); } if (getEndDate() != null) { _hashCode += getEndDate().hashCode(); } if (getRegion() != null) { _hashCode += getRegion().hashCode(); } if (getCountry() != null) { _hashCode += getCountry().hashCode(); } _hashCode += getFormType(); if (getGroups() != null) { _hashCode += getGroups().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(AvaFileForm.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "AvaFileForm")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("avaFileFormId"); elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "AvaFileFormId")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("formName"); elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "FormName")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("returnName"); elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ReturnName")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("description"); elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "Description")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("effDate"); elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "EffDate")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "dateTime")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("endDate"); elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "EndDate")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "dateTime")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("region"); elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "Region")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("country"); elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "Country")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("formType"); elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "FormType")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("groups"); elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "Groups")); elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ArrayOfAvaFileFormGroup")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new com.avalara.avatax.services.base.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
32.351039
125
0.611365
3c6b20f1e4718ded6027e72bc8c09d1082a11977
6,316
/* * 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.beam.sdk.extensions.sql.impl.transform; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.beam.sdk.extensions.sql.BeamRecordSqlType; import org.apache.beam.sdk.extensions.sql.BeamSqlRecordHelper; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.SimpleFunction; import org.apache.beam.sdk.values.BeamRecord; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollectionView; import org.apache.calcite.rel.core.JoinRelType; import org.apache.calcite.util.Pair; /** * Collections of {@code PTransform} and {@code DoFn} used to perform JOIN operation. */ public class BeamJoinTransforms { /** * A {@code SimpleFunction} to extract join fields from the specified row. */ public static class ExtractJoinFields extends SimpleFunction<BeamRecord, KV<BeamRecord, BeamRecord>> { private final boolean isLeft; private final List<Pair<Integer, Integer>> joinColumns; public ExtractJoinFields(boolean isLeft, List<Pair<Integer, Integer>> joinColumns) { this.isLeft = isLeft; this.joinColumns = joinColumns; } @Override public KV<BeamRecord, BeamRecord> apply(BeamRecord input) { // build the type // the name of the join field is not important List<String> names = new ArrayList<>(joinColumns.size()); List<Integer> types = new ArrayList<>(joinColumns.size()); for (int i = 0; i < joinColumns.size(); i++) { names.add("c" + i); types.add(isLeft ? BeamSqlRecordHelper.getSqlRecordType(input).getFieldTypeByIndex( joinColumns.get(i).getKey()) : BeamSqlRecordHelper.getSqlRecordType(input).getFieldTypeByIndex( joinColumns.get(i).getValue())); } BeamRecordSqlType type = BeamRecordSqlType.create(names, types); // build the row List<Object> fieldValues = new ArrayList<>(joinColumns.size()); for (int i = 0; i < joinColumns.size(); i++) { fieldValues.add(input .getFieldValue(isLeft ? joinColumns.get(i).getKey() : joinColumns.get(i).getValue())); } return KV.of(new BeamRecord(type, fieldValues), input); } } /** * A {@code DoFn} which implement the sideInput-JOIN. */ public static class SideInputJoinDoFn extends DoFn<KV<BeamRecord, BeamRecord>, BeamRecord> { private final PCollectionView<Map<BeamRecord, Iterable<BeamRecord>>> sideInputView; private final JoinRelType joinType; private final BeamRecord rightNullRow; private final boolean swap; public SideInputJoinDoFn(JoinRelType joinType, BeamRecord rightNullRow, PCollectionView<Map<BeamRecord, Iterable<BeamRecord>>> sideInputView, boolean swap) { this.joinType = joinType; this.rightNullRow = rightNullRow; this.sideInputView = sideInputView; this.swap = swap; } @ProcessElement public void processElement(ProcessContext context) { BeamRecord key = context.element().getKey(); BeamRecord leftRow = context.element().getValue(); Map<BeamRecord, Iterable<BeamRecord>> key2Rows = context.sideInput(sideInputView); Iterable<BeamRecord> rightRowsIterable = key2Rows.get(key); if (rightRowsIterable != null && rightRowsIterable.iterator().hasNext()) { Iterator<BeamRecord> it = rightRowsIterable.iterator(); while (it.hasNext()) { context.output(combineTwoRowsIntoOne(leftRow, it.next(), swap)); } } else { if (joinType == JoinRelType.LEFT) { context.output(combineTwoRowsIntoOne(leftRow, rightNullRow, swap)); } } } } /** * A {@code SimpleFunction} to combine two rows into one. */ public static class JoinParts2WholeRow extends SimpleFunction<KV<BeamRecord, KV<BeamRecord, BeamRecord>>, BeamRecord> { @Override public BeamRecord apply(KV<BeamRecord, KV<BeamRecord, BeamRecord>> input) { KV<BeamRecord, BeamRecord> parts = input.getValue(); BeamRecord leftRow = parts.getKey(); BeamRecord rightRow = parts.getValue(); return combineTwoRowsIntoOne(leftRow, rightRow, false); } } /** * As the method name suggests: combine two rows into one wide row. */ private static BeamRecord combineTwoRowsIntoOne(BeamRecord leftRow, BeamRecord rightRow, boolean swap) { if (swap) { return combineTwoRowsIntoOneHelper(rightRow, leftRow); } else { return combineTwoRowsIntoOneHelper(leftRow, rightRow); } } /** * As the method name suggests: combine two rows into one wide row. */ private static BeamRecord combineTwoRowsIntoOneHelper(BeamRecord leftRow, BeamRecord rightRow) { // build the type List<String> names = new ArrayList<>(leftRow.getFieldCount() + rightRow.getFieldCount()); names.addAll(leftRow.getDataType().getFieldNames()); names.addAll(rightRow.getDataType().getFieldNames()); List<Integer> types = new ArrayList<>(leftRow.getFieldCount() + rightRow.getFieldCount()); types.addAll(BeamSqlRecordHelper.getSqlRecordType(leftRow).getFieldTypes()); types.addAll(BeamSqlRecordHelper.getSqlRecordType(rightRow).getFieldTypes()); BeamRecordSqlType type = BeamRecordSqlType.create(names, types); List<Object> fieldValues = new ArrayList<>(leftRow.getDataValues()); fieldValues.addAll(rightRow.getDataValues()); return new BeamRecord(type, fieldValues); } }
38.987654
98
0.70741
dda141eab4a3a36bf2c3567e155f6d10af7603de
2,102
/* * Weblounge: Web Content Management System * Copyright (c) 2003 - 2011 The Weblounge Team * http://entwinemedia.com/weblounge * * This program 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 * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ch.entwine.weblounge.bridge.mail; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; /** * Test case for the implementation at {@link Account}. */ public class AccountTest { /** The account under test */ protected Account account = null; /** Account host */ protected String host = "host.com"; /** Account login name */ protected String login = "login"; /** Account password */ protected String password = "password"; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { account = new Account(host, login, password); } /** * Test method for {@link ch.entwine.weblounge.bridge.mail.Account#getHost()}. */ @Test public void testGetHost() { assertEquals(host, account.getHost()); } /** * Test method for {@link ch.entwine.weblounge.bridge.mail.Account#getLogin()}. */ @Test public void testGetLogin() { assertEquals(login, account.getLogin()); } /** * Test method for {@link ch.entwine.weblounge.bridge.mail.Account#getPassword()} * . */ @Test public void testGetPassword() { assertEquals(password, account.getPassword()); } }
26.607595
83
0.693149
31092f4569a0d9c358a089c936bd2f1d03d4f18d
1,718
package OctopusConsortium.DosService1_5; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for contactType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="contactType"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="dts"/&gt; * &lt;enumeration value="itk"/&gt; * &lt;enumeration value="telno"/&gt; * &lt;enumeration value="email"/&gt; * &lt;enumeration value="faxno"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "contactType") @XmlEnum public enum EndpointTransportType { @XmlEnumValue("dts") DTS("dts"), @XmlEnumValue("itk") ITK("itk"), @XmlEnumValue("telno") TELNO("telno"), @XmlEnumValue("email") EMAIL("email"), @XmlEnumValue("faxno") FAXNO("faxno"); private final String value; EndpointTransportType(String v) { value = v; } public String value() { return value; } public boolean equalsValue(String v){ if (v == null) throw new IllegalArgumentException(v); return (this.value().equalsIgnoreCase(v)); } public static EndpointTransportType fromValue(String v) { if (v == null) throw new IllegalArgumentException(v); v = v.toLowerCase(); for (EndpointTransportType c: EndpointTransportType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
23.534247
95
0.619907
9cd93898c42125e1413d9cb61481ea4c7a22bb7d
1,249
package com.vladsch.flexmark.ext.resizable.image; import com.vladsch.flexmark.util.ast.DoNotDecorate; import com.vladsch.flexmark.util.ast.Node; import com.vladsch.flexmark.util.sequence.BasedSequence; import org.jetbrains.annotations.NotNull; public class ResizableImage extends Node implements DoNotDecorate { protected BasedSequence source = BasedSequence.NULL; protected BasedSequence text = BasedSequence.NULL; protected BasedSequence width = BasedSequence.NULL; protected BasedSequence height = BasedSequence.NULL; @NotNull @Override public BasedSequence[] getSegments() { return new BasedSequence[] { text, source, width, height }; } public ResizableImage(BasedSequence text, BasedSequence source, BasedSequence width, BasedSequence height) { super(spanningChars(text, source, width, height)); this.source = source; this.text = text; this.width = width; this.height = height; } public BasedSequence getText() { return text; } public BasedSequence getSource() { return source; } public BasedSequence getWidth() { return width; } public BasedSequence getHeight() { return height; } }
28.386364
112
0.69976
89bf3bc3d208f2c984fc50cf9c9a80514a22f8de
5,405
package io.cattle.platform.servicediscovery.deployment.impl; import io.cattle.platform.core.constants.CommonStatesConstants; import io.cattle.platform.core.constants.InstanceConstants; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.model.Service; import io.cattle.platform.core.model.ServiceExposeMap; import io.cattle.platform.engine.process.impl.ProcessCancelException; import io.cattle.platform.object.process.StandardProcess; import io.cattle.platform.object.resource.ResourcePredicate; import io.cattle.platform.process.common.util.ProcessUtils; import io.cattle.platform.servicediscovery.api.constants.ServiceDiscoveryConstants; import io.cattle.platform.servicediscovery.api.util.ServiceDiscoveryUtil; import io.cattle.platform.servicediscovery.deployment.AbstractInstanceUnit; import io.cattle.platform.servicediscovery.deployment.DeploymentUnitInstance; import io.cattle.platform.servicediscovery.deployment.impl.DeploymentManagerImpl.DeploymentServiceContext; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.Pair; public class DefaultDeploymentUnitInstance extends AbstractInstanceUnit { protected String instanceName; public DefaultDeploymentUnitInstance(DeploymentServiceContext context, String uuid, Service service, String instanceName, Instance instance, Map<String, String> labels, String launchConfigName) { super(context, uuid, service, launchConfigName); this.instanceName = instanceName; this.instance = instance; if (this.instance != null) { exposeMap = context.exposeMapDao.findInstanceExposeMap(this.instance); } } @Override public boolean isError() { return this.instance != null && this.instance.getRemoved() != null; } @Override protected void removeUnitInstance() { if (!(instance.getState().equals(CommonStatesConstants.REMOVED) || instance.getState().equals( CommonStatesConstants.REMOVING))) { try { context.objectProcessManager.scheduleStandardProcessAsync(StandardProcess.REMOVE, instance, null); } catch (ProcessCancelException e) { context.objectProcessManager.scheduleProcessInstanceAsync(InstanceConstants.PROCESS_STOP, instance, ProcessUtils.chainInData(new HashMap<String, Object>(), InstanceConstants.PROCESS_STOP, InstanceConstants.PROCESS_REMOVE)); } } } @Override public DeploymentUnitInstance create(Map<String, Object> deployParams) { if (createNew()) { Map<String, Object> launchConfigData = populateLaunchConfigData(deployParams); Pair<Instance, ServiceExposeMap> instanceMapPair = context.exposeMapDao.createServiceInstance(launchConfigData, service, this.instanceName); this.instance = instanceMapPair.getLeft(); this.exposeMap = instanceMapPair.getRight(); } if (instance.getState().equalsIgnoreCase(CommonStatesConstants.REQUESTED)) { context.objectProcessManager.scheduleStandardProcessAsync(StandardProcess.CREATE, instance, null); } if (exposeMap.getState().equalsIgnoreCase(CommonStatesConstants.REQUESTED)) { context.objectProcessManager.scheduleStandardProcessAsync(StandardProcess.CREATE, exposeMap, null); } this.instance = context.objectManager.reload(this.instance); return this; } @SuppressWarnings("unchecked") protected Map<String, Object> populateLaunchConfigData(Map<String, Object> deployParams) { Map<String, Object> launchConfigData = ServiceDiscoveryUtil.buildServiceInstanceLaunchData(service, deployParams, launchConfigName, context.allocatorService); launchConfigData.put("name", this.instanceName); Object labels = launchConfigData.get(InstanceConstants.FIELD_LABELS); if (labels != null) { String overrideHostName = ((Map<String, String>) labels) .get(ServiceDiscoveryConstants.LABEL_OVERRIDE_HOSTNAME); if (StringUtils.equalsIgnoreCase(overrideHostName, "container_name")) { launchConfigData.put(InstanceConstants.FIELD_HOSTNAME, this.instanceName); } } return launchConfigData; } @Override public boolean createNew() { return this.instance == null; } @Override public DeploymentUnitInstance waitForStartImpl() { this.instance = context.resourceMonitor.waitFor(this.instance, new ResourcePredicate<Instance>() { @Override public boolean evaluate(Instance obj) { return InstanceConstants.STATE_RUNNING.equals(obj.getState()); } }); return this; } @Override protected boolean isStartedImpl() { return context.objectManager.reload(this.instance).getState().equalsIgnoreCase(InstanceConstants.STATE_RUNNING); } @Override public void waitForNotTransitioning() { if (this.instance != null) { this.instance = context.resourceMonitor.waitForNotTransitioning(this.instance); } } }
42.559055
123
0.701943
bef2a4c4bc4f146cb2750332d5ea5d0ce2ab243d
2,338
/* * Copyright 2022 EPAM Systems. * * 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 com.epam.digital.data.platform.registry.regulation.validation.cli.support; import com.epam.digital.data.platform.registry.regulation.validation.cli.model.RegulationFiles; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.cli.Options; import org.apache.commons.lang3.StringUtils; public class CommandLineOptionsConverter { public RegulationFiles convert(Options options) { return RegulationFiles.builder() .globalVarsFiles(getFilesIfAny(CommandLineArg.GLOBAL_VARS, options)) .bpAuthFiles(getFilesIfAny(CommandLineArg.BP_AUTH, options)) .bpTrembitaFiles(getFilesIfAny(CommandLineArg.BP_TREMBITA, options)) .bpTrembitaConfig(getFilesIfAny(CommandLineArg.BP_TREMBITA_CONFIG, options)) .rolesFiles(getFilesIfAny(CommandLineArg.ROLES, options)) .bpmnFiles(getFilesIfAny(CommandLineArg.BPMN, options)) .dmnFiles(getFilesIfAny(CommandLineArg.DMN, options)) .formFiles(getFilesIfAny(CommandLineArg.FORMS, options)) .settingsFiles(getFilesIfAny(CommandLineArg.SETTINGS, options)) .liquibaseFiles(getFilesIfAny(CommandLineArg.LIQUIBASE, options)) .build(); } private Collection<File> getFilesIfAny(CommandLineArg regulationTypeArgOption, Options options) { if (options.hasOption(regulationTypeArgOption.getArgOptionName())) { var option = options.getOption(regulationTypeArgOption.getArgOptionName()); var optionValues = option.getValues(); return Stream.of(optionValues).filter(StringUtils::isNotBlank).map(File::new).collect(Collectors.toSet()); } return Collections.emptySet(); } }
43.296296
112
0.763901
6af3487d0b20219fa40cee716d4af16948381bec
3,520
/* * Copyright 2015-2018 Canoo Engineering AG. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.canoo.dp.impl.platform.projector.client.media; import com.canoo.dp.impl.platform.projector.client.css.CssHelper; import com.canoo.dp.impl.platform.projector.client.css.DefaultPropertyBasedCssMetaData; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.css.CssMetaData; import javafx.css.StyleConverter; import javafx.css.Styleable; import javafx.scene.Node; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.MultipleSelectionModel; import javafx.scene.control.Skin; import javafx.scene.input.MouseEvent; import java.util.List; public class StructuredListCell<T> extends ListCell<T> { private ObjectProperty<Node> leftContent; private ObjectProperty<Node> centerContent; private ObjectProperty<Node> rightContent; public StructuredListCell() { getStyleClass().add("structured-list-cell"); leftContent = new SimpleObjectProperty<>(); centerContent = new SimpleObjectProperty<>(); rightContent = new SimpleObjectProperty<>(); addEventHandler(MouseEvent.MOUSE_CLICKED, e -> simpleSelect()); } public Node getLeftContent() { return leftContent.get(); } public void setLeftContent(Node leftContent) { this.leftContent.set(leftContent); } public ObjectProperty<Node> leftContentProperty() { return leftContent; } public Node getCenterContent() { return centerContent.get(); } public void setCenterContent(Node centerContent) { this.centerContent.set(centerContent); } public ObjectProperty<Node> centerContentProperty() { return centerContent; } public Node getRightContent() { return rightContent.get(); } public void setRightContent(Node rightContent) { this.rightContent.set(rightContent); } public ObjectProperty<Node> rightContentProperty() { return rightContent; } @Override public List<CssMetaData<? extends Styleable, ?>> getControlCssMetaData() { return StyleableProperties.STYLEABLES; } @Override protected Skin<?> createDefaultSkin() { return new StructuredListCellSkin(this); } private void simpleSelect() { ListView lv = getListView(); int index = getIndex(); MultipleSelectionModel sm = lv.getSelectionModel(); lv.getSelectionModel().clearAndSelect(index); } private static class StyleableProperties { private static final DefaultPropertyBasedCssMetaData<StructuredListCell, Number> SPACING = CssHelper.createMetaData("-fx-spacing", StyleConverter.getSizeConverter(), "spacing", 0); private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES = CssHelper.createCssMetaDataList(StructuredListCell.getClassCssMetaData(), SPACING); } }
31.711712
188
0.724432
4f5b50e74b49340dd550142271b558c5a058b3c2
189
package io.zhenyed; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserMapper extends BaseMapper<User> { }
18.9
55
0.814815
7fc243f11b6449eb30a9641e095ee4eaedb52a24
1,258
package com.github.swissquote.carnotzet.maven.plugin; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; import com.github.swissquote.carnotzet.core.runtime.log.LogListener; import com.github.swissquote.carnotzet.core.runtime.log.StdOutLogPrinter; import com.github.swissquote.carnotzet.maven.plugin.impl.Utils; /** * Stop all containers<br> * if -Dservice=... is passed, ony the chosen service will be stopped * a comma-separated list of regexp is also supported */ @Mojo(name = "stop", defaultPhase = LifecyclePhase.NONE, threadSafe = true, requiresDependencyResolution = ResolutionScope.COMPILE) public class StopMojo extends AbstractZetMojo { @Override public void executeInternal() throws MojoExecutionException, MojoFailureException { if (isFollow()) { LogListener printer = new StdOutLogPrinter(Utils.getServiceNames(getCarnotzet()), 0, true); getRuntime().registerLogListener(printer); } if (getService() == null) { getRuntime().stop(); } else { getRuntime().stop(getService()); } } }
33.105263
131
0.779809