text stringlengths 10 2.72M |
|---|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package privacypreserving;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import java.awt.Color;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.Font;
/**
*
* @author
*/
public class datacip extends javax.swing.JFrame {
Connection con = null;
Statement st1 = null;
Statement st2 = null;
Statement st3 = null;
ResultSet rs1 = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "multi";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
public static String datakey;
public static ArrayList cipdatabn=new ArrayList();
public static ArrayList cipdataan=new ArrayList();
public static ArrayList cipdatapn=new ArrayList();
public static ArrayList cipdatay=new ArrayList();
/**
* Creates new form datacip
*/
public datacip() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jXTitledPanel1 = new org.jdesktop.swingx.JXTitledPanel();
jPanel2 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel3.setForeground(new Color(255, 250, 250));
jPanel3 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jPanel4 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField1.setEditable(false);
jLabel2 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jXHyperlink1 = new org.jdesktop.swingx.JXHyperlink();
jXHyperlink1.setForeground(new Color(0, 0, 0));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Privacy-Preserving Multi-Keyword Ranked Search");
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
org.jdesktop.swingx.border.DropShadowBorder dropShadowBorder1 = new org.jdesktop.swingx.border.DropShadowBorder();
dropShadowBorder1.setShowLeftShadow(true);
dropShadowBorder1.setShowTopShadow(true);
jXTitledPanel1.setBorder(dropShadowBorder1);
jXTitledPanel1.setTitle(" Privacy-Preserving Multi-Keyword Ranked Search");
jXTitledPanel1.setTitleFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jPanel2.setBackground(new Color(0, 139, 139));
jPanel2.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
jLabel3.setText("Data Ciphering");
jPanel3.setBackground(new Color(255, 255, 153));
jPanel3.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jButton1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jButton1.setText("Original Data");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(57)
.addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 143, GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 32, GroupLayout.PREFERRED_SIZE)
.addGap(21))
);
jPanel3.setLayout(jPanel3Layout);
jPanel4.setBackground(new Color(255, 255, 153));
jPanel4.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane2.setViewportView(jTable2);
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N
jLabel1.setText("Cipher Technique");
jTextField1.setText("Advance Encryption Standard");
jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N
jLabel2.setText("Enter 16 bytes key");
jButton2.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jButton2.setText("Data Cipher");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jXHyperlink1.setText("Next");
jXHyperlink1.setFont(new Font("Times New Roman", Font.BOLD, 24)); // NOI18N
jXHyperlink1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jXHyperlink1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(11)
.addComponent(jTextField1, GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE))
.addComponent(jLabel2))
.addContainerGap())
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(30)
.addComponent(jButton2, GroupLayout.PREFERRED_SIZE, 128, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
.addComponent(jXHyperlink1, GroupLayout.PREFERRED_SIZE, 54, GroupLayout.PREFERRED_SIZE)
.addGap(36))
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(107)
.addComponent(jTextField2, GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE)
.addContainerGap())
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(18)
.addGroup(jPanel4Layout.createParallelGroup(Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(19)
.addGroup(jPanel4Layout.createParallelGroup(Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addComponent(jScrollPane2, GroupLayout.PREFERRED_SIZE, 304, GroupLayout.PREFERRED_SIZE)
.addGap(18)
.addGroup(jPanel4Layout.createParallelGroup(Alignment.BASELINE)
.addComponent(jButton2, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE)
.addComponent(jXHyperlink1, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel4.setLayout(jPanel4Layout);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jPanel3, GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(jPanel4, GroupLayout.PREFERRED_SIZE, 287, GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(0, 229, Short.MAX_VALUE)
.addComponent(jLabel3)
.addGap(238))))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(15)
.addComponent(jLabel3)
.addGap(18)
.addGroup(jPanel2Layout.createParallelGroup(Alignment.LEADING)
.addComponent(jPanel4, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, GroupLayout.DEFAULT_SIZE, 469, Short.MAX_VALUE))
.addContainerGap())
);
jPanel2.setLayout(jPanel2Layout);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jXTitledPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jXTitledPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
try{
DefaultTableModel model1=new DefaultTableModel();
model1.addColumn("SL NO");
model1.addColumn("Book Name");
model1.addColumn("Author Name");
model1.addColumn("Publisher");
model1.addColumn("Year");
jTable1.setModel(model1);
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
con.setAutoCommit(false);
st1 = con.createStatement();
rs1 = st1.executeQuery("SELECT * FROM keyword");
int i=0;
while(rs1.next()){
model1.insertRow(i, new Object[]{"", ""});
String s1 = rs1.getString(1);
model1.setValueAt(s1, i, 0);
String s2 = rs1.getString(2);
model1.setValueAt(s2, i, 1);
String s3 = rs1.getString(3);
model1.setValueAt(s3, i, 2);
String s4 = rs1.getString(4);
model1.setValueAt(s4, i, 3);
String s5 = rs1.getString(5);
model1.setValueAt(s5, i++, 4);
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
try{
DefaultTableModel model1=new DefaultTableModel();
model1.addColumn("SL NO");
model1.addColumn("Book Name");
model1.addColumn("Author Name");
model1.addColumn("Publisher");
model1.addColumn("Year");
jTable2.setModel(model1);
BufferedWriter bw=new BufferedWriter(new FileWriter("./data.txt"));
datakey=jTextField2.getText();
AESencrp aes=new AESencrp();
rs1 = st1.executeQuery("SELECT * FROM keyword");
int i=0;
while(rs1.next()){
String s1 = rs1.getString(1);
String s2 = rs1.getString(2);
String s3 = rs1.getString(3);
String s4 = rs1.getString(4);
String s5 = rs1.getString(5);
String wordEnc1 = AESencrp.encrypt(s2,datakey);
String wordEnc2 = AESencrp.encrypt(s3,datakey);
String wordEnc3 = AESencrp.encrypt(s4,datakey);
String wordEnc4 = AESencrp.encrypt(s5,datakey);
cipdatabn.add(wordEnc1);
cipdataan.add(wordEnc2);
cipdatapn.add(wordEnc3);
cipdatay.add(wordEnc4);
bw.write(wordEnc1+"\n"+wordEnc2+"\n"+wordEnc3+"\n"+wordEnc4+"\n");
bw.newLine();
model1.insertRow(i, new Object[]{"", ""});
model1.setValueAt((i+1), i, 0);
model1.setValueAt(wordEnc1, i, 1);
model1.setValueAt(wordEnc2, i, 2);
model1.setValueAt(wordEnc3, i, 3);
model1.setValueAt(wordEnc4, i++, 4);
}
bw.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jXHyperlink1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jXHyperlink1ActionPerformed
// TODO add your handling code here:
try{
indexcip ic=new indexcip();
ic.setLocationRelativeTo(null);
ic.setVisible(true);
}
catch(Exception e){
System.out.println(e.getMessage());
}
}//GEN-LAST:event_jXHyperlink1ActionPerformed
/**
* @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(datacip.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(datacip.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(datacip.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(datacip.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 datacip().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private org.jdesktop.swingx.JXHyperlink jXHyperlink1;
private org.jdesktop.swingx.JXTitledPanel jXTitledPanel1;
// End of variables declaration//GEN-END:variables
}
|
package com.croxx.hgwechat.req.didiumbrella;
public class ReqDidiUmbrellaAuth {
private String js_code;
public ReqDidiUmbrellaAuth() {
}
/* Getters & Setters */
public String getJs_code() {
return js_code;
}
public void setJs_code(String js_code) {
this.js_code = js_code;
}
}
|
package com.groovybot.engine;
public interface GroovyEngine {
Object execute(final String script);
} |
/**
*
*/
package com.travelportal.controllers;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import play.Play;
import play.data.DynamicForm;
import play.db.jpa.Transactional;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Http.MultipartFormData.FilePart;
import play.mvc.Result;
import com.fasterxml.jackson.databind.JsonNode;
import com.travelportal.domain.BillingInformation;
import com.travelportal.domain.BusinessCommunication;
import com.travelportal.domain.City;
import com.travelportal.domain.Country;
import com.travelportal.domain.Currency;
import com.travelportal.domain.HotelAmenities;
import com.travelportal.domain.HotelAttractions;
import com.travelportal.domain.HotelBrands;
import com.travelportal.domain.HotelHealthAndSafety;
import com.travelportal.domain.HotelMealPlan;
import com.travelportal.domain.HotelPrivateContacts;
import com.travelportal.domain.HotelProfile;
import com.travelportal.domain.HotelServices;
import com.travelportal.domain.HotelStarRatings;
import com.travelportal.domain.ImgPath;
import com.travelportal.domain.InternalContacts;
import com.travelportal.domain.Location;
import com.travelportal.domain.MarketPolicyTypes;
import com.travelportal.domain.MealType;
import com.travelportal.domain.NightLife;
import com.travelportal.domain.Salutation;
import com.travelportal.domain.ShoppingFacility;
import com.travelportal.domain.TransportationDirection;
import com.travelportal.domain.rooms.ChildPolicies;
import com.travelportal.vm.AreaAttractionsSuppVM;
import com.travelportal.vm.AreaAttractionsVM;
import com.travelportal.vm.ChildpoliciVM;
import com.travelportal.vm.HotelDescription;
import com.travelportal.vm.HotelHealthAndSafetyVM;
import com.travelportal.vm.HotelamenitiesVM;
import com.travelportal.vm.HotelmealVM;
import com.travelportal.vm.TransportationDirectionsSuppVM;
import com.travelportal.vm.TransportationDirectionsVM;
//import views.html.home;
/**
* @author
*
*/
public class HotelProfileController extends Controller {
final static String rootDir = Play.application().configuration().getString("mail.storage.path");
static {
createRootDir();
}
public static void createRootDir() {
File file = new File(rootDir);
if (!file.exists()) {
file.mkdir();
}
}
/* public static Result home() {
//Accept the supplier code as parameter...
return ok(home.render("Home Page"));
}
*/
public static Result viewSupplierProfile(final Long supplierCode) {
//Accept the supplier code as parameter...
System.out.println("view supplier profile...");
//return ok(home.render("Home Page", supplierCode));
return ok();
}
@Transactional(readOnly=false)
public static Result saveGeneralInfo() {
DynamicForm form = DynamicForm.form().bindFromRequest();
HotelProfile hotelprofile;
if(form.get("supplierCode") == null || form.get("supplierCode") == "")
{
hotelprofile = new HotelProfile();
}
else
{
hotelprofile = HotelProfile.findById(Long.parseLong(form.get("supplierCode")));
}
hotelprofile.setHotelName(form.get("hotelNm"));
hotelprofile.setSupplierName(form.get("hotelNm"));
//hotelprofile.setCompanyNm(form.get("companyNm"));
hotelprofile.setAddress(form.get("hotelAddr"));
hotelprofile.setCountry(Country.getCountryByCode(Integer.parseInt(form.get("countryCode"))));
hotelprofile.setCurrency(Currency.getCurrencyByCode(Integer.parseInt(form.get("currencyCode"))));
hotelprofile.setCity(City.getCityByCode(Integer.parseInt(form.get("cityCode"))));
hotelprofile.setPartOfChain(form.get("hotelPartOfChain"));
hotelprofile.setHotelEmailAddr(form.get("email"));
hotelprofile.setMarketPolicyType(MarketPolicyTypes.getMarketPolicyTypesIdByCode(Integer.parseInt(form.get("marketSpecificPolicyCode"))));
hotelprofile.setHoteBrands(form.get("brandHotelCode"));
hotelprofile.setPassword(form.get("primaryPasswd"));
hotelprofile.setStartRatings(HotelStarRatings.getHotelRatingsById(Integer.parseInt(form.get("startRating"))));
hotelprofile.setVerifyPassword(form.get("verifiedPasswd"));
if(form.get("supplierCode") == null || form.get("supplierCode") == "")
{
hotelprofile.save();
}
else
{
hotelprofile.merge();
}
Map<String,Object> map = new HashMap<String,Object>();
map.put("ID", hotelprofile.getSupplier_code());
map.put("NAME", hotelprofile.getHotelName());
map.put("ADDR",hotelprofile.getAddress());
map.put("Currency",hotelprofile.getCurrency().getCurrencyName());
return ok(Json.toJson(map));
}
@Transactional(readOnly=false)
public static Result saveAmenities() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelamenitiesVM.class);
HotelamenitiesVM hotelamenitiesVM = Json.fromJson(json, HotelamenitiesVM.class);
HotelProfile hotelprofile = HotelProfile.findById(Long.parseLong(form.get("supplierCode")));
hotelprofile.setAmenities(HotelAmenities.getallhotelamenities(hotelamenitiesVM.getAmenities()));
return ok();
}
@Transactional(readOnly=false)
public static Result saveUpdateHealthSafety() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafetyVM healthAndSafetyVM = Json.fromJson(json, HotelHealthAndSafetyVM.class);
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(healthAndSafetyVM.getSupplierCode());
if(hAndSafety == null)
{
hAndSafety=new HotelHealthAndSafety();
hAndSafety.setFireRisk(healthAndSafetyVM.getFireRisk());
hAndSafety.setHaccpCertify(healthAndSafetyVM.getHaccpCertify());
hAndSafety.setInternalFire(healthAndSafetyVM.getInternalFire());
hAndSafety.setLocalTourist(healthAndSafetyVM.getLocalTourist());
hAndSafety.setPublicLiability(healthAndSafetyVM.getPublicLiability());
hAndSafety.setRecordsForFire(healthAndSafetyVM.getRecordsForFire());
hAndSafety.setRecordsForHealth(healthAndSafetyVM.getRecordsForHealth());
if(healthAndSafetyVM.fireRiskexpiryDate != null){
try {
hAndSafety.setFireRiskexpiryDate(format.parse(healthAndSafetyVM.fireRiskexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(healthAndSafetyVM.haccpCertifyexpiryDate != null){
try {
hAndSafety.setHaccpCertifyexpiryDate(format.parse(healthAndSafetyVM.haccpCertifyexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(healthAndSafetyVM.internalFireexpiryDate != null){
try {
hAndSafety.setInternalFireexpiryDate(format.parse(healthAndSafetyVM.internalFireexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(healthAndSafetyVM.localTouristexpiryDate != null){
try {
hAndSafety.setLocalTouristexpiryDate(format.parse(healthAndSafetyVM.localTouristexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(healthAndSafetyVM.publicLiabilityexpiryDate != null){
try {
hAndSafety.setPublicLiabilityexpiryDate(format.parse(healthAndSafetyVM.publicLiabilityexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(healthAndSafetyVM.recordsForFireexpiryDate != null){
try {
hAndSafety.setRecordsForFireexpiryDate(format.parse(healthAndSafetyVM.recordsForFireexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(healthAndSafetyVM.recordsForHealthexpiryDate != null){
try {
hAndSafety.setRecordsForHealthexpiryDate(format.parse(healthAndSafetyVM.recordsForHealthexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//hAndSafety.setf
/*try {
hAndSafety.setExpiryDate(format.parse(healthAndSafetyVM.getExpiryDate()));
hAndSafety.setExpiryDate1(format.parse(healthAndSafetyVM.getExpiryDate1()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.save();
}
else
{
hAndSafety.setFireRisk(healthAndSafetyVM.getFireRisk());
hAndSafety.setHaccpCertify(healthAndSafetyVM.getHaccpCertify());
hAndSafety.setInternalFire(healthAndSafetyVM.getInternalFire());
hAndSafety.setLocalTourist(healthAndSafetyVM.getLocalTourist());
hAndSafety.setPublicLiability(healthAndSafetyVM.getPublicLiability());
hAndSafety.setRecordsForFire(healthAndSafetyVM.getRecordsForFire());
hAndSafety.setRecordsForHealth(healthAndSafetyVM.getRecordsForHealth());
if(healthAndSafetyVM.fireRiskexpiryDate != null){
try {
hAndSafety.setFireRiskexpiryDate(format.parse(healthAndSafetyVM.fireRiskexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(healthAndSafetyVM.haccpCertifyexpiryDate != null){
try {
hAndSafety.setHaccpCertifyexpiryDate(format.parse(healthAndSafetyVM.haccpCertifyexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(healthAndSafetyVM.internalFireexpiryDate != null){
try {
hAndSafety.setInternalFireexpiryDate(format.parse(healthAndSafetyVM.internalFireexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(healthAndSafetyVM.localTouristexpiryDate != null){
try {
hAndSafety.setLocalTouristexpiryDate(format.parse(healthAndSafetyVM.localTouristexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(healthAndSafetyVM.publicLiabilityexpiryDate != null){
try {
hAndSafety.setPublicLiabilityexpiryDate(format.parse(healthAndSafetyVM.publicLiabilityexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(healthAndSafetyVM.recordsForFireexpiryDate != null){
try {
hAndSafety.setRecordsForFireexpiryDate(format.parse(healthAndSafetyVM.recordsForFireexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(healthAndSafetyVM.recordsForHealthexpiryDate != null){
try {
hAndSafety.setRecordsForHealthexpiryDate(format.parse(healthAndSafetyVM.recordsForHealthexpiryDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*try {
hAndSafety.setExpiryDate(format.parse(healthAndSafetyVM.getExpiryDate()));
hAndSafety.setExpiryDate1(format.parse(healthAndSafetyVM.getExpiryDate1()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
hAndSafety.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result saveUpdateFirePrecaution() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafetyVM healthAndSafetyVM = Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(healthAndSafetyVM.getSupplierCode());
if(hAndSafety == null)
{
hAndSafety=new HotelHealthAndSafety();
hAndSafety.setWorkingFireAlarm(healthAndSafetyVM.getWorkingFireAlarm());
hAndSafety.setSmokeDetectorsInPublicArea(healthAndSafetyVM.getSmokeDetectorsInPublicArea());
hAndSafety.setSmokeDetectorsInApartment(healthAndSafetyVM.getSmokeDetectorsInApartment());
hAndSafety.setSmokeDetectorsInGuestBedroom(healthAndSafetyVM.getSmokeDetectorsInGuestBedroom());
hAndSafety.setSystemAtLeastAnnually(healthAndSafetyVM.getSystemAtLeastAnnually());
hAndSafety.setInternalFireAlarmTest(healthAndSafetyVM.getInternalFireAlarmTest());
hAndSafety.setExtinguishersInAllArea(healthAndSafetyVM.getExtinguishersInAllArea());
hAndSafety.setEmergencyLightingInstall(healthAndSafetyVM.getEmergencyLightingInstall());
hAndSafety.setLimitedWalkingAbilities(healthAndSafetyVM.getLimitedWalkingAbilities());
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.save();
}
else
{
hAndSafety.setWorkingFireAlarm(healthAndSafetyVM.getWorkingFireAlarm());
hAndSafety.setSmokeDetectorsInPublicArea(healthAndSafetyVM.getSmokeDetectorsInPublicArea());
hAndSafety.setSmokeDetectorsInApartment(healthAndSafetyVM.getSmokeDetectorsInApartment());
hAndSafety.setSmokeDetectorsInGuestBedroom(healthAndSafetyVM.getSmokeDetectorsInGuestBedroom());
hAndSafety.setSystemAtLeastAnnually(healthAndSafetyVM.getSystemAtLeastAnnually());
hAndSafety.setInternalFireAlarmTest(healthAndSafetyVM.getInternalFireAlarmTest());
hAndSafety.setExtinguishersInAllArea(healthAndSafetyVM.getExtinguishersInAllArea());
hAndSafety.setEmergencyLightingInstall(healthAndSafetyVM.getEmergencyLightingInstall());
hAndSafety.setLimitedWalkingAbilities(healthAndSafetyVM.getLimitedWalkingAbilities());
hAndSafety.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result saveUpdateExitsAndCorridor() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafetyVM healthAndSafetyVM = Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(healthAndSafetyVM.getSupplierCode());
if(hAndSafety == null)
{
hAndSafety=new HotelHealthAndSafety();
hAndSafety.setHowManyExits(healthAndSafetyVM.getHowManyExits());
hAndSafety.setUnlockedAtAllTime(healthAndSafetyVM.getUnlockedAtAllTime());
hAndSafety.setExitsClearlySigned(healthAndSafetyVM.getExitsClearlySigned());
hAndSafety.setRoutesIlluminated(healthAndSafetyVM.getRoutesIlluminated());
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.setUsableStaircaseFromAllFloors(healthAndSafetyVM.getUsableStaircaseFromAllFloors());
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.save();
}
else
{
hAndSafety.setHowManyExits(healthAndSafetyVM.getHowManyExits());
hAndSafety.setUnlockedAtAllTime(healthAndSafetyVM.getUnlockedAtAllTime());
hAndSafety.setExitsClearlySigned(healthAndSafetyVM.getExitsClearlySigned());
hAndSafety.setRoutesIlluminated(healthAndSafetyVM.getRoutesIlluminated());
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.setUsableStaircaseFromAllFloors(healthAndSafetyVM.getUsableStaircaseFromAllFloors());
hAndSafety.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result saveUpdateAirCondition() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafetyVM healthAndSafetyVM = Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(healthAndSafetyVM.getSupplierCode());
if(hAndSafety == null)
{
hAndSafety=new HotelHealthAndSafety();
hAndSafety.setCentral(healthAndSafetyVM.getCentral());
hAndSafety.setIndependentUnits(healthAndSafetyVM.getIndependentUnits());
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.save();
}
else
{
hAndSafety.setCentral(healthAndSafetyVM.getCentral());
hAndSafety.setIndependentUnits(healthAndSafetyVM.getIndependentUnits());
hAndSafety.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result saveUpdateLifts() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafetyVM healthAndSafetyVM = Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(healthAndSafetyVM.getSupplierCode());
if(hAndSafety == null)
{
hAndSafety=new HotelHealthAndSafety();
hAndSafety.setFloorsAccessible(healthAndSafetyVM.getFloorsAccessible());
hAndSafety.setInternalClosingDoor(healthAndSafetyVM.getInternalClosingDoor());
hAndSafety.setRelevantSignageDisplay(healthAndSafetyVM.getRelevantSignageDisplay());
hAndSafety.setNoSmoking(healthAndSafetyVM.getNoSmoking());
hAndSafety.setNoUnaccompaniedChildren(healthAndSafetyVM.getNoUnaccompaniedChildren());
hAndSafety.setEventOfFire(healthAndSafetyVM.getEventOfFire());
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.save();
}
else
{
hAndSafety.setFloorsAccessible(healthAndSafetyVM.getFloorsAccessible());
hAndSafety.setInternalClosingDoor(healthAndSafetyVM.getInternalClosingDoor());
hAndSafety.setRelevantSignageDisplay(healthAndSafetyVM.getRelevantSignageDisplay());
hAndSafety.setNoSmoking(healthAndSafetyVM.getNoSmoking());
hAndSafety.setNoUnaccompaniedChildren(healthAndSafetyVM.getNoUnaccompaniedChildren());
hAndSafety.setEventOfFire(healthAndSafetyVM.getEventOfFire());
hAndSafety.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result saveUpdateBedroomsAsndBalconies() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafetyVM healthAndSafetyVM = Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(healthAndSafetyVM.getSupplierCode());
if(hAndSafety == null)
{
hAndSafety=new HotelHealthAndSafety();
hAndSafety.setFireSafetyInstructionsPosted(healthAndSafetyVM.getFireSafetyInstructionsPosted());
hAndSafety.setElectricsAutomaticallyDisconnect(healthAndSafetyVM.getElectricsAutomaticallyDisconnect());
hAndSafety.setRoomsHaveBalconies(healthAndSafetyVM.getRoomsHaveBalconies());
hAndSafety.setBalconiesAtLeast1m(healthAndSafetyVM.getBalconiesAtLeast1m());
hAndSafety.setGapsGreaterThan10cm(healthAndSafetyVM.getGapsGreaterThan10cm());
hAndSafety.setAnyAdjoiningRooms(healthAndSafetyVM.getAnyAdjoiningRooms());
hAndSafety.setHowMany(healthAndSafetyVM.getHowMany());
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.save();
}
else
{
hAndSafety.setFireSafetyInstructionsPosted(healthAndSafetyVM.getFireSafetyInstructionsPosted());
hAndSafety.setElectricsAutomaticallyDisconnect(healthAndSafetyVM.getElectricsAutomaticallyDisconnect());
hAndSafety.setRoomsHaveBalconies(healthAndSafetyVM.getRoomsHaveBalconies());
hAndSafety.setBalconiesAtLeast1m(healthAndSafetyVM.getBalconiesAtLeast1m());
hAndSafety.setGapsGreaterThan10cm(healthAndSafetyVM.getGapsGreaterThan10cm());
hAndSafety.setAnyAdjoiningRooms(healthAndSafetyVM.getAnyAdjoiningRooms());
hAndSafety.setHowMany(healthAndSafetyVM.getHowMany());
hAndSafety.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result saveUpdateKitchenAndHygiene() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafetyVM healthAndSafetyVM = Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(healthAndSafetyVM.getSupplierCode());
if(hAndSafety == null)
{
hAndSafety=new HotelHealthAndSafety();
hAndSafety.setSelfCateringAccommodation(healthAndSafetyVM.getSelfCateringAccommodation());
hAndSafety.setSelfCateringAccommodationHaveFull(healthAndSafetyVM.getSelfCateringAccommodationHaveFull());
hAndSafety.setAllKitchenAppliancesRegularly(healthAndSafetyVM.getAllKitchenAppliancesRegularly());
hAndSafety.setMainKitchen(healthAndSafetyVM.getMainKitchen());
hAndSafety.setStagesOfFoodPreparation(healthAndSafetyVM.getStagesOfFoodPreparation());
hAndSafety.setPremisesAdequatelyProofed(healthAndSafetyVM.getPremisesAdequatelyProofed());
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.save();
}
else
{
hAndSafety.setSelfCateringAccommodation(healthAndSafetyVM.getSelfCateringAccommodation());
hAndSafety.setSelfCateringAccommodationHaveFull(healthAndSafetyVM.getSelfCateringAccommodationHaveFull());
hAndSafety.setAllKitchenAppliancesRegularly(healthAndSafetyVM.getAllKitchenAppliancesRegularly());
hAndSafety.setMainKitchen(healthAndSafetyVM.getMainKitchen());
hAndSafety.setStagesOfFoodPreparation(healthAndSafetyVM.getStagesOfFoodPreparation());
hAndSafety.setPremisesAdequatelyProofed(healthAndSafetyVM.getPremisesAdequatelyProofed());
hAndSafety.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result saveUpdateAdditionalInfo() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafetyVM healthAndSafetyVM = Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(healthAndSafetyVM.getSupplierCode());
if(hAndSafety == null)
{
hAndSafety=new HotelHealthAndSafety();
hAndSafety.setAdditionalInformationOrComments(healthAndSafetyVM.getAdditionalInformationOrComments());
hAndSafety.setName(healthAndSafetyVM.getName());
hAndSafety.setDesignation(healthAndSafetyVM.getDesignation());
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.save();
}
else
{
hAndSafety.setAdditionalInformationOrComments(healthAndSafetyVM.getAdditionalInformationOrComments());
hAndSafety.setName(healthAndSafetyVM.getName());
hAndSafety.setDesignation(healthAndSafetyVM.getDesignation());
hAndSafety.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result saveUpdateGaswaterHeaters() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafetyVM healthAndSafetyVM = Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(healthAndSafetyVM.getSupplierCode());
if(hAndSafety == null)
{
hAndSafety=new HotelHealthAndSafety();
hAndSafety.setGasWaterHeaters(healthAndSafetyVM.getGasWaterHeaters());
hAndSafety.setInternal(healthAndSafetyVM.getInternal());
hAndSafety.setExternal(healthAndSafetyVM.getExternal());
hAndSafety.setServicing(healthAndSafetyVM.getServicing());
hAndSafety.setMaintenance(healthAndSafetyVM.getMaintenance());
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.save();
}
else
{
hAndSafety.setGasWaterHeaters(healthAndSafetyVM.getGasWaterHeaters());
hAndSafety.setInternal(healthAndSafetyVM.getInternal());
hAndSafety.setExternal(healthAndSafetyVM.getExternal());
hAndSafety.setServicing(healthAndSafetyVM.getServicing());
hAndSafety.setMaintenance(healthAndSafetyVM.getMaintenance());
hAndSafety.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result saveUpdateChildrenFaciliti() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafetyVM healthAndSafetyVM = Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(healthAndSafetyVM.getSupplierCode());
if(hAndSafety == null)
{
hAndSafety=new HotelHealthAndSafety();
hAndSafety.setInternalChildrenPlayArea(healthAndSafetyVM.getInternalChildrenPlayArea());
hAndSafety.setExternalChildrenPlayArea(healthAndSafetyVM.getExternalChildrenPlayArea());
hAndSafety.setSuperviseTheKidClub(healthAndSafetyVM.getSuperviseTheKidClub());
hAndSafety.setQualityChecksOfEquipmentAndFurniture(healthAndSafetyVM.getQualityChecksOfEquipmentAndFurniture());
if(!healthAndSafetyVM.getMonthkid().isEmpty())
{
int i=0;
for(String month : healthAndSafetyVM.getMonthkid()){
if(i==0){
hAndSafety.setMonthkid(month);
} else {
hAndSafety.setMonthkid(hAndSafety.getMonthkid()+","+month);
}
i++;
}
}
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.save();
}
else
{
hAndSafety.setInternalChildrenPlayArea(healthAndSafetyVM.getInternalChildrenPlayArea());
hAndSafety.setExternalChildrenPlayArea(healthAndSafetyVM.getExternalChildrenPlayArea());
hAndSafety.setSuperviseTheKidClub(healthAndSafetyVM.getSuperviseTheKidClub());
hAndSafety.setQualityChecksOfEquipmentAndFurniture(healthAndSafetyVM.getQualityChecksOfEquipmentAndFurniture());
if(!healthAndSafetyVM.getMonthkid().isEmpty())
{
int i=0;
for(String month : healthAndSafetyVM.getMonthkid()){
if(i==0){
hAndSafety.setMonthkid(month);
} else {
hAndSafety.setMonthkid(hAndSafety.getMonthkid()+","+month);
}
i++;
}
}
hAndSafety.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result saveUpdateSwimmingPool() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafetyVM healthAndSafetyVM = Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(healthAndSafetyVM.getSupplierCode());
if(hAndSafety == null)
{
hAndSafety=new HotelHealthAndSafety();
hAndSafety.setPoolRulesAndRegulation(healthAndSafetyVM.getPoolRulesAndRegulation());
hAndSafety.setOpeningClosingTimes(healthAndSafetyVM.getOpeningClosingTimes());
hAndSafety.setDepthInformation(healthAndSafetyVM.getDepthInformation());
hAndSafety.setNoDiving(healthAndSafetyVM.getNoDiving());
hAndSafety.setNoUnaccompaniedChildrenPool(healthAndSafetyVM.getNoUnaccompaniedChildrenPool());
hAndSafety.setLifesavingEquipment(healthAndSafetyVM.getLifesavingEquipment());
hAndSafety.setGlassAroundThePoolArea(healthAndSafetyVM.getGlassAroundThePoolArea());
hAndSafety.setLifeguardOrQualifiedPerson(healthAndSafetyVM.getLifeguardOrQualifiedPerson());
hAndSafety.setThereChildrenPool(healthAndSafetyVM.getThereChildrenPool());
hAndSafety.setSeparatedFromTheAdultPool(healthAndSafetyVM.getSeparatedFromTheAdultPool());
hAndSafety.setSufficientDepthMarkings(healthAndSafetyVM.getSufficientDepthMarkings());
hAndSafety.setThePoolCleanedDaily(healthAndSafetyVM.getThePoolCleanedDaily());
hAndSafety.setRecordsKept(healthAndSafetyVM.getRecordsKept());
hAndSafety.setHeatedPoolInTheProperty(healthAndSafetyVM.getHeatedPoolInTheProperty());
if(!healthAndSafetyVM.getMonthOperational() .isEmpty())
{
int i=0;
for(String month : healthAndSafetyVM.getMonthOperational()){
if(i==0){
hAndSafety.setMonthOperational(month);
} else {
hAndSafety.setMonthOperational(hAndSafety.getMonthOperational()+","+month);
}
i++;
}
}
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.save();
}
else
{
hAndSafety.setPoolRulesAndRegulation(healthAndSafetyVM.getPoolRulesAndRegulation());
hAndSafety.setOpeningClosingTimes(healthAndSafetyVM.getOpeningClosingTimes());
hAndSafety.setDepthInformation(healthAndSafetyVM.getDepthInformation());
hAndSafety.setNoDiving(healthAndSafetyVM.getNoDiving());
hAndSafety.setNoUnaccompaniedChildrenPool(healthAndSafetyVM.getNoUnaccompaniedChildrenPool());
hAndSafety.setLifesavingEquipment(healthAndSafetyVM.getLifesavingEquipment());
hAndSafety.setGlassAroundThePoolArea(healthAndSafetyVM.getGlassAroundThePoolArea());
hAndSafety.setLifeguardOrQualifiedPerson(healthAndSafetyVM.getLifeguardOrQualifiedPerson());
hAndSafety.setThereChildrenPool(healthAndSafetyVM.getThereChildrenPool());
hAndSafety.setSeparatedFromTheAdultPool(healthAndSafetyVM.getSeparatedFromTheAdultPool());
hAndSafety.setSufficientDepthMarkings(healthAndSafetyVM.getSufficientDepthMarkings());
hAndSafety.setThePoolCleanedDaily(healthAndSafetyVM.getThePoolCleanedDaily());
hAndSafety.setRecordsKept(healthAndSafetyVM.getRecordsKept());
hAndSafety.setHeatedPoolInTheProperty(healthAndSafetyVM.getHeatedPoolInTheProperty());
if(!healthAndSafetyVM.getMonthOperational() .isEmpty())
{
int i=0;
for(String month : healthAndSafetyVM.getMonthOperational()){
if(i==0){
hAndSafety.setMonthOperational(month);
} else {
hAndSafety.setMonthOperational(hAndSafety.getMonthOperational()+","+month);
}
i++;
}
}
hAndSafety.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result saveUpdateCCTVstatus() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafetyVM healthAndSafetyVM = Json.fromJson(json, HotelHealthAndSafetyVM.class);
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(healthAndSafetyVM.getSupplierCode());
if(hAndSafety == null)
{
hAndSafety=new HotelHealthAndSafety();
if(!healthAndSafetyVM.getCctvArea() .isEmpty())
{
int i=0;
for(String month : healthAndSafetyVM.getCctvArea()){
if(i==0){
hAndSafety.setCctvArea(month);
} else {
hAndSafety.setCctvArea(hAndSafety.getCctvArea()+","+month);
}
i++;
}
}
hAndSafety.setSupplierCode(healthAndSafetyVM.getSupplierCode());
hAndSafety.save();
}
else
{
if(!healthAndSafetyVM.getCctvArea() .isEmpty())
{
int i=0;
for(String month : healthAndSafetyVM.getCctvArea()){
if(i==0){
hAndSafety.setCctvArea(month);
} else {
hAndSafety.setCctvArea(hAndSafety.getCctvArea()+","+month);
}
i++;
}
}
hAndSafety.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result savefiles() {
DynamicForm form = DynamicForm.form().bindFromRequest();
HotelHealthAndSafety hAndSafety=HotelHealthAndSafety.findById(Long.parseLong(form.get("supplierCode")));
FilePart picture = request().body().asMultipartFormData().getFile("file1");
createDir(rootDir,hAndSafety.getSupplierCode(), hAndSafety.getId());
String fileName = picture.getFilename();
String imgPath = rootDir + File.separator +Long.parseLong(form.get("supplierCode"))+File.separator+ "HealthSafety"+ File.separator + +hAndSafety.getId()+ File.separator+fileName;
File src = picture.getFile();
OutputStream out = null;
BufferedImage image = null;
File f = new File(imgPath);
try {
Files.copy(src.toPath(),f.toPath(),java.nio.file.StandardCopyOption.REPLACE_EXISTING);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out != null) out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ImgPath path = new ImgPath();
path.setImgpath(imgPath);
path.setDocname(fileName);
path.setDatetime(new Timestamp(System.currentTimeMillis()));
path.save();
hAndSafety.addImgpath(path);
hAndSafety.save();
//getdocument
List<HotelHealthAndSafety> docInfo = HotelHealthAndSafety.getdocument(hAndSafety.getId());
return ok(Json.toJson(docInfo));
}
public static void createDir(String rootDir, long supplierCode, int subID) {
File file3 = new File(rootDir + File.separator+supplierCode +File.separator+ "HealthSafety"+File.separator+subID);
if (!file3.exists()) {
file3.mkdirs();
}
}
@Transactional(readOnly=false)
public static Result deleteDocument(int docId,int id) {
HotelHealthAndSafety healthAndSafety =HotelHealthAndSafety.HealthSafetyfindById(docId);
/*ImgPath deletePath = null;
for(ImgPath path : healthAndSafety.getImgpath()){
if(path.getImgpathId() == id);
deletePath = path;
}*/
ImgPath imgPath = ImgPath.getImagPathById(id);
File currentFile = new File(imgPath.getImgpath());
currentFile.delete();
healthAndSafety.getImgpath().remove(imgPath);
imgPath.delete();
//healthAndSafety.setImgpath(null);
healthAndSafety.merge();
return ok();
}
@Transactional(readOnly=false)
public static Result updateMealPolicy() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelmealVM.class);
HotelmealVM hotelmealvm = Json.fromJson(json, HotelmealVM.class);
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
HotelMealPlan hotelmealplan = HotelMealPlan.findById(Integer.parseInt(form.get("id")));
try {
hotelmealplan.setFromPeriod(format.parse(hotelmealvm.getFromPeriod()));
hotelmealplan.setToPeriod(format.parse(hotelmealvm.getToPeriod()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hotelmealplan.setRestaurants(hotelmealvm.getRestaurants());
hotelmealplan.setMealPlanNm(hotelmealvm.getMealPlanNm());
hotelmealplan.setRate(hotelmealvm.getRate());
hotelmealplan.setSupplierCode(hotelmealvm.getSupplierCode());
hotelmealplan.setTaxIncluded(hotelmealvm.getTaxIncluded());
hotelmealplan.setTaxvalue(hotelmealvm.getTaxvalue());
hotelmealplan.setTaxtype(hotelmealvm.getTaxtype());
hotelmealplan.setMealType(MealType.getMealTypeIdByCode(hotelmealvm.getMealType()));
for(ChildpoliciVM vm : hotelmealvm.getChild()){
ChildPolicies childPolicies = ChildPolicies.findById(vm.getChildPolicyId());
childPolicies.setAllowedChildAgeFrom(vm.getAllowedChildAgeFrom());
childPolicies.setAllowedChildAgeTo(vm.getAllowedChildAgeTo());
childPolicies.setCharge(vm.getCharge());
childPolicies.setChargeType(vm.getChargeType());
childPolicies.setChildtaxvalue(vm.getChildtaxvalue());
childPolicies.setChildtaxtype(vm.getChildtaxtype());
childPolicies.merge();
hotelmealplan.addChild(childPolicies);
}
hotelmealplan.merge();
return ok();
}
@Transactional(readOnly=false)
public static Result saveMealPolicy() {
JsonNode json = request().body().asJson();
Json.fromJson(json, HotelmealVM.class);
HotelmealVM hotelmealvm = Json.fromJson(json, HotelmealVM.class);
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
HotelMealPlan hotelmealplan = new HotelMealPlan();
try {
hotelmealplan.setFromPeriod(format.parse(hotelmealvm.getFromPeriod()));
hotelmealplan.setToPeriod(format.parse(hotelmealvm.getToPeriod()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hotelmealplan.setRestaurants(hotelmealvm.getRestaurants());
hotelmealplan.setMealPlanNm(hotelmealvm.getMealPlanNm());
hotelmealplan.setRate(hotelmealvm.getRate());
hotelmealplan.setSupplierCode(hotelmealvm.getSupplierCode());
hotelmealplan.setTaxIncluded(hotelmealvm.getTaxIncluded());
hotelmealplan.setTaxvalue(hotelmealvm.getTaxvalue());
hotelmealplan.setTaxtype(hotelmealvm.getTaxtype());
hotelmealplan.setMealType(MealType.getMealTypeIdByCode(hotelmealvm.getMealType()));
for(ChildpoliciVM vm : hotelmealvm.getChild()){
ChildPolicies childPolicies = new ChildPolicies();
childPolicies.setAllowedChildAgeFrom(vm.getAllowedChildAgeFrom());
childPolicies.setAllowedChildAgeTo(vm.getAllowedChildAgeTo());
childPolicies.setCharge(vm.getCharge());
childPolicies.setChargeType(vm.getChargeType());
childPolicies.setChildtaxvalue(vm.getChildtaxvalue());
childPolicies.setChildtaxtype(vm.getChildtaxtype());
childPolicies.save();
hotelmealplan.addChild(childPolicies);
}
hotelmealplan.save();
return ok();
}
@Transactional(readOnly=false)
public static Result deleteChile(int id) {
HotelMealPlan hotelmealplan = HotelMealPlan.findById(id);
for(ChildPolicies policies : hotelmealplan.getChild()){
policies.delete();
}
hotelmealplan.setChild(null);
hotelmealplan.merge();
return ok();
}
@Transactional(readOnly=false)
public static Result deleteMealPolicy(int id) {
HotelMealPlan hotelmealplan = HotelMealPlan.findById(id);
for(ChildPolicies policies : hotelmealplan.getChild()){
policies.delete();
}
hotelmealplan.delete();
return ok();
}
@Transactional(readOnly=false)
public static Result saveAttraction() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, AreaAttractionsSuppVM.class);
AreaAttractionsSuppVM areaattractionssuppVM = Json.fromJson(json, AreaAttractionsSuppVM.class);
HotelProfile hotelprofile = HotelProfile.findById(Long.parseLong(form.get("supplierCode")));
String attractionsuccess="";
//hotelprofile.setHotelareaattraction(null);
for(AreaAttractionsVM vm : areaattractionssuppVM.getAreaInfo()){
if(vm.getName() != "")
{
HotelAttractions hotelattractions = new HotelAttractions();
if(hotelattractions.attractionrepeat(vm.getName()) == null)
{
hotelattractions.setDistanceType(vm.getKm());
hotelattractions.setDistance(vm.getDistance());
hotelattractions.setTimeRequireInMinutes(vm.getMinutes());
hotelattractions.setAttractionNm(vm.getName());
hotelattractions.save();
hotelprofile.addHotelareaattraction(hotelattractions);
attractionsuccess = "yes";
}
else
{
// hotelprofile.addHotelareaattraction(hotelattractions.attractionrepeat(vm.getname()));
attractionsuccess = "no";
}
}
}
return ok(attractionsuccess);
}
@Transactional(readOnly=false)
public static Result saveTransportDir() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, TransportationDirectionsSuppVM.class);
TransportationDirectionsSuppVM transportationdirectionsSuppVM = Json.fromJson(json, TransportationDirectionsSuppVM.class);
HotelProfile hotelprofile = HotelProfile.findById(Long.parseLong(form.get("supplierCode")));
String successdata="";
hotelprofile.setTransportCode(null);
for(TransportationDirectionsVM vm : transportationdirectionsSuppVM.getFindLocation()){
TransportationDirection transportationDirection=new TransportationDirection();
if(transportationDirection.checklocationexe(vm.getLocationName()) == null) {
transportationDirection.setLocationName(vm.getLocationName());
transportationDirection.setLocationAddr(vm.getLocationAddr());
transportationDirection.save();
hotelprofile.addTransportCode(transportationDirection);
successdata="yes";
} else {
hotelprofile.addTransportCode(transportationDirection.checklocationexe(vm.getLocationName()));
successdata="no";
}
}
return ok(successdata);
}
@Transactional(readOnly=false)
public static Result updateDescription() {
JsonNode json = request().body().asJson();
DynamicForm form = DynamicForm.form().bindFromRequest();
Json.fromJson(json, HotelDescription.class);
HotelDescription hoteldescription = Json.fromJson(json, HotelDescription.class);
HotelProfile hotelprofile = HotelProfile.findById(Long.parseLong(form.get("supplierCode")));
System.out.println("hoteldescription=="+hoteldescription.getDescription());
hotelprofile.setHotelProfileDesc(hoteldescription.getDescription());
hotelprofile.setLocation(Location.getlocationIdByCode(hoteldescription.getHotelLocation()));
if(hoteldescription.getShoppingFacilityCode() != 0){
hotelprofile.setShoppingFacility(ShoppingFacility.getShoppingFacilityByCode(hoteldescription.getShoppingFacilityCode()));
}
if(hoteldescription.getNightLifeCode() != 0){
hotelprofile.setNightLife(NightLife.getNightLifeByCode(hoteldescription.getNightLifeCode()));
}
System.out.println("get services=="+hoteldescription.getServices());
hotelprofile.setServices(HotelServices.getallhotelservice(hoteldescription.getServices()));
hotelprofile.setlocation1(hoteldescription.getLocation1());
hotelprofile.setlocation2(hoteldescription.getLocation2());
hotelprofile.setlocation3(hoteldescription.getLocation3());
hotelprofile.setSupplier_code(Long.parseLong(form.get("supplierCode")));
hotelprofile.merge();
return ok();
}
@Transactional(readOnly=false)
public static Result updateInternalInfo() {
DynamicForm form = DynamicForm.form().bindFromRequest();
HotelProfile hotelprofile = HotelProfile.findById(Long.parseLong(form.get("supplierCode")));
hotelprofile.setHotelGeneralManager(form.get("genMgrName"));
hotelprofile.setGeneralMgrEmail(form.get("genMgrEmail"));
if(form.get("builtYear") != null && form.get("builtYear") != ""){
hotelprofile.setHotelBuiltYear(Integer.parseInt(form.get("builtYear")));
}
if(form.get("renovationYear") != null && form.get("renovationYear") != ""){
hotelprofile.setHotelRenovationYear(Integer.parseInt(form.get("renovationYear")));
}
hotelprofile.setHotelWebSite(form.get("webSiteUrl"));
if(form.get("noOffloor") != null && form.get("noOffloor") != ""){
hotelprofile.setNoOfFloors(Integer.parseInt(form.get("noOffloor")));
}else{
hotelprofile.setNoOfFloors(0);
}
hotelprofile.setNoOfRooms(Integer.parseInt(form.get("noOfRoom")));
hotelprofile.setFireSafetyCompliance(form.get("safetyCompliance"));
hotelprofile.merge();
InternalContacts internalcontact = InternalContacts.findById(Long.parseLong(form.get("supplierCode")));
if(internalcontact == null)
{
internalcontact=new InternalContacts();
internalcontact.setGuestTelCityCode(Integer.parseInt(form.get("guestTelCode")));
internalcontact.setGuestTelValue(Integer.parseInt(form.get("guestTel")));
if(form.get("guestFaxCode") != null && form.get("guestFaxCode") != ""){
internalcontact.setGuestFaxCityCode(Integer.parseInt(form.get("guestFaxCode")));
}
if(form.get("guestFax") != null && form.get("guestFax") != ""){
internalcontact.setGuestFaxValue(Integer.parseInt(form.get("guestFax")));
}
internalcontact.setDirectTelCityCode(Integer.parseInt(form.get("directTelCode")));
internalcontact.setDirectTelValue(Integer.parseInt(form.get("directTelNo")));
if(form.get("directFaxCode") != null && form.get("directFaxCode") != ""){
internalcontact.setDirectFaxCityCode(Integer.parseInt(form.get("directFaxCode")));
}
if(form.get("directFaxNo") != null && form.get("directFaxNo") != ""){
internalcontact.setDirectFaxValue(Integer.parseInt(form.get("directFaxNo")));
}
internalcontact.setSupplierCode(Long.parseLong(form.get("supplierCode")));
internalcontact.setCheckTimePolicy(form.get("checkTimePolicy"));
if(form.get("checkTimePolicy").equals("yes")){
internalcontact.setCheckInTime(null);
internalcontact.setCheckInType(null);
internalcontact.setCheckOutTime(null);
internalcontact.setCheckOutType(null);
}else{
internalcontact.setCheckInTime(form.get("checkInTime"));
internalcontact.setCheckInType(form.get("checkInType"));
internalcontact.setCheckOutTime(form.get("checkOutTime"));
internalcontact.setCheckOutType(form.get("checkOutType"));
}
internalcontact.setRoomVoltage(form.get("roomVoltage"));
internalcontact.save();
}
else
{
internalcontact.setGuestTelCityCode(Integer.parseInt(form.get("guestTelCode")));
internalcontact.setGuestTelValue(Integer.parseInt(form.get("guestTel")));
if(form.get("guestFaxCode") != null && form.get("guestFaxCode") != ""){
internalcontact.setGuestFaxCityCode(Integer.parseInt(form.get("guestFaxCode")));
}
if(form.get("guestFax") != null && form.get("guestFax") != ""){
internalcontact.setGuestFaxValue(Integer.parseInt(form.get("guestFax")));
}
internalcontact.setDirectTelCityCode(Integer.parseInt(form.get("directTelCode")));
internalcontact.setDirectTelValue(Integer.parseInt(form.get("directTelNo")));
if(form.get("directFaxCode") != null && form.get("directFaxCode") != ""){
internalcontact.setDirectFaxCityCode(Integer.parseInt(form.get("directFaxCode")));
}
if(form.get("directFaxNo") != null && form.get("directFaxNo") != ""){
internalcontact.setDirectFaxValue(Integer.parseInt(form.get("directFaxNo")));
}
internalcontact.setRoomVoltage(form.get("roomVoltage"));
internalcontact.setCheckTimePolicy(form.get("checkTimePolicy"));
if(form.get("checkTimePolicy").equals("Yes")){
internalcontact.setCheckInTime(null);
internalcontact.setCheckInType(null);
internalcontact.setCheckOutTime(null);
internalcontact.setCheckOutType(null);
}else{
internalcontact.setCheckInTime(form.get("checkInTime"));
internalcontact.setCheckInType(form.get("checkInType"));
internalcontact.setCheckOutTime(form.get("checkOutTime"));
internalcontact.setCheckOutType(form.get("checkOutType"));
}
internalcontact.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result updateContactInfo() {
DynamicForm form = DynamicForm.form().bindFromRequest();
HotelPrivateContacts hotelprivatecontacts = HotelPrivateContacts.findById(Long.parseLong(form.get("supplierCode")));
if(hotelprivatecontacts == null)
{
hotelprivatecontacts =new HotelPrivateContacts();
hotelprivatecontacts.setSupplierCode(Long.parseLong(form.get("supplierCode")));
hotelprivatecontacts.setMainContactPersonName(form.get("cPersonName"));
hotelprivatecontacts.setMainContactPersonTitle(form.get("cTitle"));
hotelprivatecontacts.setMainContactTelNo(Integer.parseInt(form.get("dTelNo")));
hotelprivatecontacts.setMainContactTelCode(Integer.parseInt(form.get("dTelCode")));
hotelprivatecontacts.setMainContactPhoneNo(Integer.parseInt(form.get("mPhoneNo")));
hotelprivatecontacts.setMainContactFaxNo(Integer.parseInt(form.get("dFaxNo")));
hotelprivatecontacts.setMainContactFaxCode(Integer.parseInt(form.get("dFaxCode")));
if(form.get("dExtNo") != null && form.get("dExtNo") != ""){
hotelprivatecontacts.setMainContactExt(Integer.parseInt(form.get("dExtNo")));
}
hotelprivatecontacts.setMainContactEmailAddr(form.get("dEmailAddr"));
hotelprivatecontacts.setTollFreeNo(form.get("dTollFreeTelNo"));
hotelprivatecontacts.setReservationSameAsMainContact(form.get("reservationDetailSame"));
hotelprivatecontacts.setReservationContactPersonName(form.get("rContactName"));
hotelprivatecontacts.setReservationContactPersonTitle(form.get("rTitle"));
hotelprivatecontacts.setReservationContactTelNo(Integer.parseInt(form.get("rDirectTelNo")));
hotelprivatecontacts.setReservationContactTelCode(Integer.parseInt(form.get("rDirectTelCode")));
hotelprivatecontacts.setDeptTelNo(Integer.parseInt(form.get("rDeptTelNo")));
hotelprivatecontacts.setDeptTelCode(Integer.parseInt(form.get("rDeptTelCode")));
hotelprivatecontacts.setDeptFaxNo(Integer.parseInt(form.get("rDeptFaxNo")));
hotelprivatecontacts.setDeptFaxCode(Integer.parseInt(form.get("rDeptFaxCode")));
if(form.get("rExtNo") != null && form.get("rExtNo") != ""){
hotelprivatecontacts.setDeptExtNo(Integer.parseInt(form.get("rExtNo")));
}
if(form.get("deptExtNo") != null){
hotelprivatecontacts.setReservationContactExt(Integer.parseInt(form.get("deptExtNo")));
}
hotelprivatecontacts.setReservationContactEmailAddr(form.get("rEmailAddr"));
hotelprivatecontacts.setSalutation_salutation_id(Salutation.getsalutationIdIdByCode(Integer.parseInt(form.get("salutationCode"))));
hotelprivatecontacts.save();
}
else
{
hotelprivatecontacts.setMainContactPersonName(form.get("cPersonName"));
hotelprivatecontacts.setMainContactPersonTitle(form.get("cTitle"));
hotelprivatecontacts.setMainContactTelNo(Integer.parseInt(form.get("dTelNo")));
hotelprivatecontacts.setMainContactTelCode(Integer.parseInt(form.get("dTelCode")));
hotelprivatecontacts.setMainContactPhoneNo(Integer.parseInt(form.get("mPhoneNo")));
hotelprivatecontacts.setMainContactFaxNo(Integer.parseInt(form.get("dFaxNo")));
hotelprivatecontacts.setMainContactFaxCode(Integer.parseInt(form.get("dFaxCode")));
if(form.get("dExtNo") != null && form.get("dExtNo") != ""){
hotelprivatecontacts.setMainContactExt(Integer.parseInt(form.get("dExtNo")));
}
hotelprivatecontacts.setMainContactEmailAddr(form.get("dEmailAddr"));
hotelprivatecontacts.setTollFreeNo(form.get("dTollFreeTelNo"));
hotelprivatecontacts.setReservationSameAsMainContact(form.get("reservationDetailSame"));
hotelprivatecontacts.setReservationContactPersonName(form.get("rContactName"));
hotelprivatecontacts.setReservationContactPersonTitle(form.get("rTitle"));
hotelprivatecontacts.setReservationContactTelNo(Integer.parseInt(form.get("rDirectTelNo")));
hotelprivatecontacts.setReservationContactTelCode(Integer.parseInt(form.get("rDirectTelCode")));
hotelprivatecontacts.setDeptTelNo(Integer.parseInt(form.get("rDeptTelNo")));
hotelprivatecontacts.setDeptTelCode(Integer.parseInt(form.get("rDeptTelCode")));
hotelprivatecontacts.setDeptFaxNo(Integer.parseInt(form.get("rDeptFaxNo")));
hotelprivatecontacts.setDeptFaxCode(Integer.parseInt(form.get("rDeptFaxCode")));
if(form.get("rExtNo") != null && form.get("rExtNo") != ""){
hotelprivatecontacts.setDeptExtNo(Integer.parseInt(form.get("rExtNo")));
}
if(form.get("deptExtNo") != null && form.get("deptExtNo") != ""){
hotelprivatecontacts.setReservationContactExt(Integer.parseInt(form.get("deptExtNo")));
}
hotelprivatecontacts.setReservationContactEmailAddr(form.get("rEmailAddr"));
hotelprivatecontacts.setSalutation_salutation_id(Salutation.getsalutationIdIdByCode(Integer.parseInt(form.get("salutationCode"))));
hotelprivatecontacts.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result updateBillingInfo() {
DynamicForm form = DynamicForm.form().bindFromRequest();
BillingInformation billinginfo = BillingInformation.findById(Long.parseLong(form.get("supplierCode")));
if(billinginfo == null)
{
billinginfo =new BillingInformation();
billinginfo.setInvoiceToHotel(form.get("invoiceToHotel"));
billinginfo.setFirstName(form.get("aFirstName"));
billinginfo.setLastName(form.get("aLastName"));
billinginfo.setTitle(form.get("title"));
billinginfo.setSalutationCode(Salutation.getsalutationIdIdByCode(Integer.parseInt(form.get("salutationCode"))));
billinginfo.setEmailAddr(form.get("dEmailAddr"));
billinginfo.setTelNo(Integer.parseInt(form.get("dTelNo")));
billinginfo.setTelNoCode(Integer.parseInt(form.get("dTelCode")));
billinginfo.setFaxNo(Integer.parseInt(form.get("dFaxNo")));
billinginfo.setFaxNoCode(Integer.parseInt(form.get("dFaxCode")));
billinginfo.setMainContactPhoneNo(Integer.parseInt(form.get("mobileNo")));
if(form.get("dExtNo") != null && form.get("dExtNo") != ""){
billinginfo.setExt(Integer.parseInt(form.get("dExtNo")));;
}
billinginfo.setSupplierCode(Long.parseLong(form.get("supplierCode")));
billinginfo.setBankservice(form.get("bankToBankTransfer"));
billinginfo.setBankName(form.get("bankName"));
if(form.get("accountNo") != null)
{
billinginfo.setAccountNo(Long.parseLong(form.get("accountNo")));
}
else
{
billinginfo.setAccountNo(null);
}
billinginfo.setAccountType(form.get("accountType"));
billinginfo.setBranchName(form.get("branchName"));
billinginfo.setSwiftCode(form.get("swiftCode"));
billinginfo.save();
}
else
{
billinginfo.setInvoiceToHotel(form.get("invoiceToHotel"));
billinginfo.setFirstName(form.get("aFirstName"));
billinginfo.setLastName(form.get("aLastName"));
billinginfo.setTitle(form.get("title"));
billinginfo.setEmailAddr(form.get("dEmailAddr"));
billinginfo.setTelNo(Integer.parseInt(form.get("dTelNo")));
billinginfo.setTelNoCode(Integer.parseInt(form.get("dTelCode")));
billinginfo.setFaxNo(Integer.parseInt(form.get("dFaxNo")));
billinginfo.setFaxNoCode(Integer.parseInt(form.get("dFaxCode")));
billinginfo.setMainContactPhoneNo(Integer.parseInt(form.get("mobileNo")));
if(form.get("dExtNo") != null && form.get("dExtNo") != ""){
billinginfo.setExt(Integer.parseInt(form.get("dExtNo")));;
}
billinginfo.setBankservice(form.get("bankToBankTransfer"));
billinginfo.setBankName(form.get("bankName"));
if(form.get("accountNo") != null)
{
billinginfo.setAccountNo(Long.parseLong(form.get("accountNo")));
}
else
{
billinginfo.setAccountNo(null);
}
billinginfo.setAccountType(form.get("accountType"));
billinginfo.setBranchName(form.get("branchName"));
billinginfo.setSwiftCode(form.get("swiftCode"));
billinginfo.setSalutationCode(Salutation.getsalutationIdIdByCode(Integer.parseInt(form.get("salutationCode"))));
billinginfo.merge();
}
return ok();
}
@Transactional(readOnly=false)
public static Result updateComunication() {
DynamicForm form = DynamicForm.form().bindFromRequest();
BusinessCommunication businesscommunication = BusinessCommunication.findById(Long.parseLong(form.get("supplierCode")));
if(businesscommunication == null)
{
businesscommunication=new BusinessCommunication();
businesscommunication.setPrimaryEmailAddr(form.get("primaryEmailAddr"));
businesscommunication.setCcEmailAddr(form.get("ccEmailAddr"));
businesscommunication.setbooking(form.get("booking"));
businesscommunication.setSupplierCode(Long.parseLong(form.get("supplierCode")));
businesscommunication.save();
}
else
{
businesscommunication.setPrimaryEmailAddr(form.get("primaryEmailAddr"));
businesscommunication.setCcEmailAddr(form.get("ccEmailAddr"));
businesscommunication.setbooking(form.get("booking"));
businesscommunication.merge();
}
return ok();
}
}
|
package com.sprmvc.web.ch5.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sprmvc.web.ch5.Profile;
import com.sprmvc.web.ch5.Spitter;
import com.sprmvc.web.ch5.Spittle;
import com.sprmvc.web.ch5.data.SpittleRepository;
import com.sprmvc.web.ch5.exc.SpitterExceptionRest;
import com.sprmvc.web.ch5.exc.SpittleNotFoundExceptionRest;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import com.sprmvc.web.ch5.exc.Error;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
@Controller
//@RestController
@RequestMapping("/spittles")
public class SpittleControllerApi {
private static final String MAX_LONG_AS_STRING = "9223372036854775807";
private SpittleRepository spittleRepository;
@Autowired
public SpittleControllerApi(SpittleRepository spittleRepository) {
this.spittleRepository = spittleRepository;
}
@RequestMapping(method = RequestMethod.GET, produces = { "application/json", "application/xml"})
public @ResponseBody Spittle spittles(
@RequestParam(value = "max",
defaultValue = MAX_LONG_AS_STRING) long max,
@RequestParam(value = "count", defaultValue = "20") int count) {
return spittleRepository.findOne(22);
}
// @RequestMapping(value = "/{spittleId}", method = RequestMethod.GET)
// public String spittle(
//// @PathVariable("spittleId") long spittleId,
// @PathVariable long spittleId,
// Model model) {
// model.addAttribute("spittle", spittleRepository.findOne(spittleId));
//// Spittle spittle = spittleRepository.findOne(spittleId);
//// if (spittle == null) {
//// throw new SpittleNotFoundException();
//// }
// return "spittle";
// }
// @RequestMapping(method = RequestMethod.POST, consumes = "application/json")
// @ResponseStatus(HttpStatus.CREATED)
// public @ResponseBody Spittle saveSpittle(@RequestBody Spittle spittle) {
// return spittleRepository.save(spittle);
// }
@RequestMapping(method = RequestMethod.POST, consumes = "application/json")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Spittle> saveSpittle(@RequestBody Spittle spittle) {
Spittle spittleR = spittleRepository.save(spittle);
HttpHeaders headers = new HttpHeaders();
URI locationUri = URI.create(
"http://localhost:8080/SpringMvcPractice/spittles/" + spittle.getId());
// ucb.path("/spittles/")
// .path(String.valueOf(spittle.getId()))
// .build()
// .toUri();
// headers.setLocation(locationUri);
headers.setLocation(locationUri);
ResponseEntity<Spittle> responseEntity =
new ResponseEntity<Spittle>(
spittle, headers, HttpStatus.CREATED);
return responseEntity;
}
// @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = { "application/json", "application/xml"})
// public @ResponseBody Spittle spittleById(@PathVariable long id) {
// return spittleRepository.findOne(id);
// }
// @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = { "application/json", "application/xml"})
// public ResponseEntity<Spittle> spittleById(@PathVariable long id) {
// Spittle spittle = spittleRepository.findOne(id);
// HttpStatus status = spittle != null ?
// HttpStatus.OK : HttpStatus.NOT_FOUND;
// return new ResponseEntity<>(spittle, status);
// }
// @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = { "application/json", "application/xml"})
// public ResponseEntity<?> spittleById(@PathVariable long id) {
// Spittle spittle = spittleRepository.findOne(id);
// if (spittle == null) {
// Error error = new Error(4, "Spittle [" + id + "] not found");
// return new ResponseEntity<Error>(error, HttpStatus.NOT_FOUND);
// }
// return new ResponseEntity<Spittle>(spittle, HttpStatus.OK);
// }
// @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = { "application/json", "application/xml"})
// public ResponseEntity<Spittle> spittleById(@PathVariable long id) {
// Spittle spittle = spittleRepository.findOne(id);
// if (spittle == null) {
// throw new SpittleNotFoundExceptionRest(id);
// }
// return new ResponseEntity<Spittle>(spittle, HttpStatus.OK);
// }
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = { "application/json", "application/xml"})
public @ResponseBody Spittle spittleById(@PathVariable long id) {
Spittle spittle = spittleRepository.findOne(id);
if (spittle == null) {
throw new SpittleNotFoundExceptionRest(id);
}
return spittle;
}
@ExceptionHandler (SpittleNotFoundExceptionRest.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public @ResponseBody Error spittleNotFound(SpittleNotFoundExceptionRest e) {
long spittleId = e.getSpittleId();
return new Error(4, "Spittle [" + spittleId + "] not found");
}
// @ExceptionHandler (SpittleNotFoundExceptionRest.class)
// public ResponseEntity<Error> spittleNotFound(SpittleNotFoundExceptionRest e) {
// long spittleId = e.getSpittleId();
// Error error = new Error(4, "Spittle [" + spittleId + "] not found");
// return new ResponseEntity<Error>(error, HttpStatus.NOT_FOUND);
// }
// public Profile fetchFacebookProfile(String id) {
// try {
// CloseableHttpClient client = HttpClients.createDefault();
//
// HttpGet request = new HttpGet("http://graph.facebook.com/" + id);
// request.setHeader("Accept", "application/json");
//
// HttpResponse response = client.execute(request);
//
// HttpEntity entity = response.getEntity();
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(entity.getContent(), Profile.class);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
public Profile fetchFacebookProfile(String id) {
RestTemplate rest = new RestTemplate();
return rest.getForObject("http://graph.facebook.com/{spitter}",
Profile.class, id);
}
// public Profile fetchFacebookProfile(String id) {
// Map<String, String> urlVariables = new HashMap<String, String>();
// urlVariables.put("id", id);
// RestTemplate rest = new RestTemplate();
// return rest.getForObject("http://graph.facebook.com/{spitter}",
// Profile.class, id);
// }
// public Spittle fetchSpittle(long id) {
// RestTemplate rest = new RestTemplate();
// ResponseEntity<Spittle> response = rest.getForEntity(
// "http://localhost:8080/SpringMvcPractice/spittles/{id}",
// Spittle.class, id);
// if (response.getStatusCode() == HttpStatus.NOT_MODIFIED) {
// try {
// throw new Exception();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// return response.getBody();
// }
public void updateSpittle(Spittle spittle) throws SpitterExceptionRest {
RestTemplate rest = new RestTemplate();
String url = "http://localhost:8080/SpringMvcPractice/spittles/"
+ spittle.getId();
rest.put(URI.create(url), spittle);
}
// public void updateSpittle(Spittle spittle) throws SpitterExceptionRest {
// RestTemplate rest = new RestTemplate();
// Map<String, String> params = new HashMap<String, String>();
// params.put("id", String.valueOf(spittle.getId()));
// rest.put("http://localhost:8080/SpringMvcPractice/spittles/{id}",
// spittle, params);
// }
public void deleteSpittle(long id) {
RestTemplate rest = new RestTemplate();
rest.delete("http://localhost:8080/SpringMvcPractice/spittles/{id}", id);
}
public Spitter postSpitterForObject(Spitter spitter) {
RestTemplate rest = new RestTemplate();
return rest.postForObject("http://localhost:8080/SpringMvcPractice/spittles/spitters",
spitter, Spitter.class);
}
// public ResponseEntity<Spitter> postSpitterForObject(Spitter spitter) {
// RestTemplate rest = new RestTemplate();
// ResponseEntity<Spitter> response = rest.postForEntity(
// "http://localhost:8080/SpringMvcPractice/spittles/spitters",
// spitter, Spitter.class);
// Spitter spitterR = response.getBody();
// URI url = response.getHeaders().getLocation();
// return response;
// }
public String postSpitter(Spitter spitter) {
RestTemplate rest = new RestTemplate();
return rest.postForLocation(
"http://localhost:8080/SpringMvcPractice/spittles/spitters",
spitter).toString();
}
public ResponseEntity<Spitter> useExchange(long spitterId) {
RestTemplate rest = new RestTemplate();
// ResponseEntity<Spitter> response = rest.exchange(
// "http://localhost:8080/SpringMvcPractice/spittles/spitters/{spitter}",
// HttpMethod.GET, null, Spitter.class, spitterId);
// Spitter spitter = response.getBody();
MultiValueMap<String, String> headers =
new LinkedMultiValueMap<String, String>();
headers.add("Accept", "application/json");
HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers);
ResponseEntity<Spitter> response = rest.exchange(
"http://localhost:8080/SpringMvcPractice/spittles/spitters/{spitter}",
HttpMethod.GET, requestEntity, Spitter.class, spitterId);
Spitter spitter = response.getBody();
return response;
}
}
|
package com.e6soft.activiti;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.e6soft.core.service.VoService;
import com.e6soft.core.web.BaseController;
public class ActivitiController extends BaseController {
public static Log log = LogFactory.getLog(ActivitiController.class);
@Resource(name="activitiVoService")
protected VoService voService;
public ActivitiController() {
super(ActivitiFactory.module);
}
}
|
package com.takshine.wxcrm.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.takshine.core.service.CRMService;
import com.takshine.wxcrm.base.common.Constants;
import com.takshine.wxcrm.base.model.BaseModel;
import com.takshine.wxcrm.base.services.BaseServiceImpl;
import com.takshine.wxcrm.base.util.WxHttpConUtil;
import com.takshine.wxcrm.domain.Bug;
import com.takshine.wxcrm.message.error.CrmError;
import com.takshine.wxcrm.message.sugar.BugReq;
import com.takshine.wxcrm.message.sugar.BugResp;
import com.takshine.wxcrm.message.sugar.ScheduleAdd;
import com.takshine.wxcrm.message.sugar.ScheduleComplete;
import com.takshine.wxcrm.message.sugar.ScheduleReq;
import com.takshine.wxcrm.message.sugar.ScheduleResp;
import com.takshine.wxcrm.service.Bug2SugarService;
/**
*
* @author lilei
*
*/
@Service("bug2SugarService")
public class Bug2SugarSerivceImpl extends BaseServiceImpl implements
Bug2SugarService {
private static Logger log = Logger.getLogger(Bug2SugarSerivceImpl.class.getName());
@Autowired
@Qualifier("cRMService")
private CRMService cRMService;
public BaseModel initObj() {
// TODO Auto-generated method stub
return null;
}
public BugResp getBugList(Bug bug) {
BugResp resp = new BugResp();
resp.setCrmaccount(bug.getCrmId());//crm id
resp.setModeltype(Constants.MODEL_TYPE_BUG);
resp.setViewtype(bug.getViewtype());
BugReq sreq = new BugReq();
sreq.setCrmaccount(bug.getCrmId());//crm id
sreq.setModeltype(Constants.MODEL_TYPE_BUG);
sreq.setViewtype(bug.getViewtype());//试图类型
sreq.setType(Constants.ACTION_SEARCH);
if(bug.getRowid()!=null&&!"".equals(bug.getRowid())){
sreq.setRowid(bug.getRowid());
}else{
sreq.setAssigner(bug.getAssignerid());
sreq.setCurrpage(bug.getCurrpage());
sreq.setStatus(bug.getStatus());
sreq.setParentid(bug.getParentid());
sreq.setPagecount(bug.getPagecount());
}
//转换为json
String jsonStr = JSONObject.fromObject(sreq).toString();
log.info("getBugList jsonStr => jsonStr is : " + jsonStr);
//单次调用sugar接口
String rst = cRMService.getWxService().getWxHttpConUtil().postJsonData(Constants.MODEL_URL_ENTRY, jsonStr, Constants.INVOKE_MULITY);
log.info("getBugList rst => rst is : " + rst);
JSONObject jsonObject = JSONObject.fromObject(rst.substring(rst.indexOf("{")));
if(!jsonObject.containsKey("errcode")){
//错误代码和消息
String count = jsonObject.getString("count");
if(!"".equals(count)
&& Integer.parseInt(count) > 0){
List<Bug> slist = (List<Bug>)JSONArray.toCollection(jsonObject.getJSONArray("bugs"), Bug.class);
resp.setBugs(slist);//bug列表
}
resp.setCount(count);//数字
}else{
String errcode = jsonObject.getString("errcode");
String errmsg = jsonObject.getString("errmsg");
log.info("getBugList errcode => errcode is : " + errcode);
log.info("getBugList errmsg => errmsg is : " + errmsg);
resp.setErrcode(errcode);
resp.setErrmsg(errmsg);
}
return resp;
}
public BugResp getBug(String rowId, String crmId) {
Bug bug = new Bug();
bug.setRowid(rowId);
bug.setCrmId(crmId);
return this.getBugList(bug);
}
public CrmError addBug(Bug obj) {
// TODO Auto-generated method stub
return null;
}
public CrmError updateBugStatus(Bug bug, String crmId) {
CrmError crmErr = new CrmError();
Map map = new HashMap();
map.put("crmaccount", bug.getCrmId());
map.put("rowid", bug.getRowid());
map.put("modeltype", Constants.MODEL_TYPE_BUG);
map.put("type", Constants.ACTION_UPDATE);
map.put("status", bug.getStatus());
map.put("log", bug.getLog());
map.put("analyze", bug.getAnalyze());
//转换为json
String jsonStr = JSONObject.fromObject(map).toString();
log.info("updateBugStatus jsonStr => jsonStr is : " + jsonStr);
//单次调用sugar接口
String rst = cRMService.getWxService().getWxHttpConUtil().postJsonData(Constants.MODEL_URL_ENTRY, jsonStr, Constants.INVOKE_MULITY);
log.info("updateBugStatus rst => rst is : " + rst);
JSONObject jsonObject = JSONObject.fromObject(rst.substring(rst.indexOf("{")));
//errormsg
String errcode = jsonObject.getString("errcode");
String errmsg = jsonObject.getString("errmsg");
log.info("updateBugStatus errcode => errcode is : " + errcode);
log.info("updateBugStatus errmsg => errmsg is : " + errmsg);
crmErr.setErrorCode(errcode);
crmErr.setErrorMsg(errmsg);
return crmErr;
}
public static void main(String[] args){
Map map = new HashMap();
map.put("crmaccount", "123213");
map.put("rowid", "2324");
map.put("modeltype", Constants.MODEL_TYPE_BUG);
map.put("type", Constants.ACTION_UPDATE);
map.put("status","234");
map.put("log", "234234");
//转换为json
String jsonStr = JSONObject.fromObject(map).toString();
System.out.print(jsonStr);
}
}
|
package com.app.artclass.database.entity;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.Index;
import androidx.room.PrimaryKey;
import androidx.room.TypeConverters;
import com.app.artclass.R;
import com.app.artclass.UserSettings;
import com.app.artclass.WEEKDAY;
import com.app.artclass.database.DatabaseConverters;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
@Entity(indices = @Index(value = {"time","weekday","name"},unique = true))
public class GroupType implements Comparable {
@PrimaryKey(autoGenerate = true)
private long groupTypeId;
@NonNull
@TypeConverters({DatabaseConverters.class})
private LocalTime time;
@NonNull
@TypeConverters({DatabaseConverters.class})
private WEEKDAY weekday;
@NonNull
private String name;
public GroupType(LocalTime time, @NonNull WEEKDAY weekday, String name) {
this.time = time;
this.weekday = weekday;
this.name = name;
}
public String getName() {
return name;
}
public LocalTime getTime() { return time; }
@Override
public String toString() {
return name;
}
@NonNull
public WEEKDAY getWeekday() {
return weekday;
}
public void setName(@NonNull String name) {
this.name = name;
}
public void setWeekday(@NonNull WEEKDAY weekday) {
this.weekday = weekday;
}
public void setGroupTypeId(long groupTypeId) {
this.groupTypeId = groupTypeId;
}
public long getGroupTypeId() {
return groupTypeId;
}
public static GroupType getNoGroup(){
return UserSettings.getInstance().getNoGroup();
}
public static GroupType getNoGroup(Context context){
return UserSettings.getInstance().getNoGroup(context);
}
@Override
public int compareTo(Object o) {
try{
return time.compareTo(((GroupType)o).time) + weekday.compareTo(((GroupType)o).getWeekday())*100;
}catch (Exception e){
return 0;
}
}
}
|
package com.pfchoice.springboot.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.pfchoice.springboot.model.HedisMeasureGroup;
import com.pfchoice.springboot.repositories.specifications.HedisMeasureGroupSpecifications;
import com.pfchoice.springboot.service.HedisMeasureGroupService;
import com.pfchoice.springboot.util.CustomErrorType;
@RestController
@RequestMapping("/api")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class HedisMeasureGroupController {
public static final Logger logger = LoggerFactory.getLogger(HedisMeasureGroupController.class);
@Autowired
HedisMeasureGroupService hedisMeasureGroupService; // Service which will do
// all data
// retrieval/manipulation work
// -------------------Retrieve All
// HedisMeasureGroups---------------------------------------------
@Secured({ "ROLE_ADMIN", "ROLE_AGENT", "ROLE_EVENT_COORDINATOR", "ROLE_CARE_COORDINATOR", "ROLE_MANAGER" })
@RequestMapping(value = "/hedisMeasureGroup/", method = RequestMethod.GET)
public ResponseEntity<?> listAllHedisMeasureGroups(@PageableDefault(page = 0, size = 100) Pageable pageRequest,
@RequestParam(value = "search", required = false) String search) {
Specification<HedisMeasureGroup> spec = new HedisMeasureGroupSpecifications(search);
Page<HedisMeasureGroup> hedisMeasureGroups = hedisMeasureGroupService.findAllHedisMeasureGroupsByPage(spec,
pageRequest);
if (hedisMeasureGroups.getTotalElements() == 0) {
System.out.println("no hedisMeasureGroups");
return new ResponseEntity(HttpStatus.NO_CONTENT);
// You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<Page<HedisMeasureGroup>>(hedisMeasureGroups, HttpStatus.OK);
}
// -------------------Retrieve Single
// HedisMeasureGroup------------------------------------------
@Secured({ "ROLE_ADMIN", "ROLE_MANAGER" })
@RequestMapping(value = "/hedisMeasureGroup/{id}", method = RequestMethod.GET)
public ResponseEntity<?> getHedisMeasureGroup(@PathVariable("id") int id) {
logger.info("Fetching HedisMeasureGroup with id {}", id);
HedisMeasureGroup hedisMeasureGroup = hedisMeasureGroupService.findById(id);
if (hedisMeasureGroup == null) {
logger.error("HedisMeasureGroup with id {} not found.", id);
return new ResponseEntity(new CustomErrorType("HedisMeasureGroup with id " + id + " not found"),
HttpStatus.NOT_FOUND);
}
return new ResponseEntity<HedisMeasureGroup>(hedisMeasureGroup, HttpStatus.OK);
}
// -------------------Create a
// HedisMeasureGroup-------------------------------------------
@Secured({ "ROLE_ADMIN", "ROLE_MANAGER" })
@RequestMapping(value = "/hedisMeasureGroup/", method = RequestMethod.POST)
public ResponseEntity<?> createHedisMeasureGroup(@RequestBody HedisMeasureGroup hedisMeasureGroup,
UriComponentsBuilder ucBuilder) {
logger.info("Creating HedisMeasureGroup : {}", hedisMeasureGroup);
if (hedisMeasureGroupService.isHedisMeasureGroupExist(hedisMeasureGroup)) {
logger.error("Unable to create. A HedisMeasureGroup with name {} already exist", hedisMeasureGroup.getId());
return new ResponseEntity(new CustomErrorType(
"Unable to create. A HedisMeasureGroup with name " + hedisMeasureGroup.getId() + " already exist."),
HttpStatus.CONFLICT);
}
hedisMeasureGroup.setCreatedBy("sarath");
hedisMeasureGroup.setUpdatedBy("sarath");
hedisMeasureGroupService.saveHedisMeasureGroup(hedisMeasureGroup);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(
ucBuilder.path("/api/hedisMeasureGroup/{id}").buildAndExpand(hedisMeasureGroup.getId()).toUri());
return new ResponseEntity<String>(headers, HttpStatus.CREATED);
}
// ------------------- Update a HedisMeasureGroup
// ------------------------------------------------
@Secured({ "ROLE_ADMIN", "ROLE_MANAGER" })
@RequestMapping(value = "/hedisMeasureGroup/{id}", method = RequestMethod.PUT)
public ResponseEntity<?> updateHedisMeasureGroup(@PathVariable("id") int id,
@RequestBody HedisMeasureGroup hedisMeasureGroup) {
logger.info("Updating HedisMeasureGroup with id {}", id);
HedisMeasureGroup currentHedisMeasureGroup = hedisMeasureGroupService.findById(id);
if (currentHedisMeasureGroup == null) {
logger.error("Unable to update. HedisMeasureGroup with id {} not found.", id);
return new ResponseEntity(
new CustomErrorType("Unable to upate. HedisMeasureGroup with id " + id + " not found."),
HttpStatus.NOT_FOUND);
}
currentHedisMeasureGroup.setCode(hedisMeasureGroup.getCode());
currentHedisMeasureGroup.setDescription(hedisMeasureGroup.getDescription());
hedisMeasureGroupService.updateHedisMeasureGroup(currentHedisMeasureGroup);
return new ResponseEntity<HedisMeasureGroup>(currentHedisMeasureGroup, HttpStatus.OK);
}
// ------------------- Delete a
// HedisMeasureGroup-----------------------------------------
@Secured({ "ROLE_ADMIN", "ROLE_MANAGER" })
@RequestMapping(value = "/hedisMeasureGroup/{id}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteHedisMeasureGroup(@PathVariable("id") int id) {
logger.info("Fetching & Deleting HedisMeasureGroup with id {}", id);
HedisMeasureGroup hedisMeasureGroup = hedisMeasureGroupService.findById(id);
if (hedisMeasureGroup == null) {
logger.error("Unable to delete. HedisMeasureGroup with id {} not found.", id);
return new ResponseEntity(
new CustomErrorType("Unable to delete. HedisMeasureGroup with id " + id + " not found."),
HttpStatus.NOT_FOUND);
}
hedisMeasureGroupService.deleteHedisMeasureGroupById(id);
return new ResponseEntity<HedisMeasureGroup>(HttpStatus.NO_CONTENT);
}
// ------------------- Delete All
// HedisMeasureGroups-----------------------------
@Secured({ "ROLE_ADMIN" })
@RequestMapping(value = "/hedisMeasureGroup/", method = RequestMethod.DELETE)
public ResponseEntity<HedisMeasureGroup> deleteAllHedisMeasureGroups() {
logger.info("Deleting All HedisMeasureGroups");
hedisMeasureGroupService.deleteAllHedisMeasureGroups();
return new ResponseEntity<HedisMeasureGroup>(HttpStatus.NO_CONTENT);
}
} |
package com.udacity.jdnd.course3.critter.service;
import com.udacity.jdnd.course3.critter.dao.EmployeeDao;
import com.udacity.jdnd.course3.critter.dao.PetDao;
import com.udacity.jdnd.course3.critter.dao.ScheduleDao;
import com.udacity.jdnd.course3.critter.entity.Schedule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ScheduleService {
@Autowired
ScheduleDao scheduleDao;
@Autowired
PetDao petDao;
@Autowired
EmployeeDao employeeDao;
public List<Schedule> getAllSchedules() {
return scheduleDao.list();
}
public List<Schedule> getScheduleByPet(Long petId) {
return scheduleDao.getSchedulesByPet(petId);
}
public List<Schedule> getScheduleByEmployee(Long employeeId) {
return scheduleDao.getSchedulesByEmployee(employeeId);
}
public List<Schedule> getScheduleForCustomer(Long customerId) {
return scheduleDao.getScheduleForCustomer(customerId);
}
public Schedule addSchedule(Schedule schedule) {
Long id = scheduleDao.addSchedule(schedule);
schedule.setId(id);
return schedule;
}
}
|
package start.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import start.service.ApiService;
/**
* @Author: Jason
* @Create: 2020/10/11 9:35
* @Description 测试api的控制器
*/
@RestController
public class ApiController {
@Autowired
private ApiService apiService;
@RequestMapping("index")
public String index(){
return apiService.test();
}
}
|
package com.coinhunter.utils.crypto.pbe;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.spec.KeySpec;
/**
* <a href=
* "http://download.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#Cipher"
* >Java ™ Cryptography Architecture(JCA) Reference Guide</a>
*
* @author SangHoon Lee
*/
public class BlockCipher extends GeneralCipher {
/**
*
* @param transformation
* is of the form: "algorithm/mode/padding" or "algorithm" <br/>
* For example, the following are valid transformations:
* "DES/ECB/PKCS5Padding" or "DES"
* @throws GeneralSecurityException
*/
public BlockCipher(String transformation) throws GeneralSecurityException {
super(transformation);
}
public Key generateKey(String transformation, byte[] keyBytes) throws GeneralSecurityException {
String algorithm = transformation;
if (transformation.indexOf('/') > -1) {
algorithm = algorithm.substring(0, algorithm.indexOf('/'));
}
// java.security.spec.KeySpec
if ("DES".equalsIgnoreCase(algorithm)) {
byte[] key = new byte[DESKeySpec.DES_KEY_LEN];
System.arraycopy(keyBytes, 0, key, 0, key.length > keyBytes.length ? keyBytes.length : key.length);
KeySpec keySpec = new DESKeySpec(key);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
return secretKey;
} else if ("DESede".equalsIgnoreCase(algorithm) || "TripleDES".equalsIgnoreCase(algorithm)) {
byte[] key = new byte[DESedeKeySpec.DES_EDE_KEY_LEN];
System.arraycopy(keyBytes, 0, key, 0, key.length > keyBytes.length ? keyBytes.length : key.length);
KeySpec keySpec = new DESedeKeySpec(key);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
return secretKey;
} else { // AES
int keyLength = Cipher.getMaxAllowedKeyLength(transformation);
byte[] key = new byte[keyLength];
System.arraycopy(keyBytes, 0, key, 0, key.length > keyBytes.length ? keyBytes.length : key.length);
SecretKey secretKey = new SecretKeySpec(key, algorithm);
return secretKey;
}
}
/**
* Initializes this cipher with a key.
*
* @param opmode
* the operation mode of this cipher (this is one of the
* following: ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE or
* UNWRAP_MODE)
* @param keyBytes
* the key
* @throws GeneralSecurityException
* @see Cipher#init(int, Key)
*/
public void init(int opmode, byte[] keyBytes) throws GeneralSecurityException {
Key key = generateKey(cipher.getAlgorithm(), keyBytes);
init(opmode, key);
}
public String encryptText(String plainText) throws IOException, GeneralSecurityException {
byte[] b = plainText.getBytes("UTF-8");
b = doFinal(b);
String encryptedText = encodeBASE64(b);
return encryptedText;
}
public String decryptText(String encryptedText) throws IOException, GeneralSecurityException {
byte[] b = decodeBASE64(encryptedText);
b = doFinal(b);
String decryptedText = new String(b, "UTF-8");
return decryptedText;
}
}
|
import javax.swing.JOptionPane;
import java.util.Random;
public class messaroundcointoss {
public static void main(String[] args)
{
int count;
int squaredAge;
for (count= 1; count<124; count++)
{
squaredAge = count*count;
if (squaredAge <2132)
{
if (squaredAge >1891)
{
System.out.println("Age : "+count +" Year :" + squaredAge );
}
}
}
}
}
|
package com.kaoqin.util;
import java.io.PrintWriter;
public class KqTool {
public static void printAlert(PrintWriter out, String message, String location){
out.println("<script language='javascript'>");
out.println("alert('" + message + "');");
out.println("window.location='" + location + "';");
out.println("</script>");
}
public static void printAlertAndGoBack(PrintWriter out, String message){
out.println("<script language='javascript'>");
out.println("alert('" + message + "');");
out.println("window.history.go(-1);");
out.println("</script>");
}
public static void printPrompt(PrintWriter out, String message, String location){
out.println("<script language='javascript'>");
out.println("window.prompt('" + message + "');");
out.println("window.location='" + location + "';");
out.println("</script>");
}
}
|
package net.youzule.spring.chapter02.BeanInherit;
/**
* @description:
* @company:
* @author:Sean
* @date:2018/7/3 10:04
**/
public class Parent {
private String name;
private int age;
private String gender;
public Parent() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Parent{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package com.hybris.backoffice.widgets.processes.settings;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class DefaultTimeRangeFactoryTest
{
@Spy
private final DefaultTimeRangeFactory timeRangeFactory = new DefaultTimeRangeFactory();
@Before
public void setUp()
{
doAnswer(inv ->
{
final Long number = (Long) inv.getArguments()[0];
return number.longValue() > 1 ? inv.getArguments()[1].toString().concat("s") : inv.getArguments()[1];
}).when(timeRangeFactory).getLabel(anyLong(), anyString());
}
@Test
public void testCreateCommaSeparatedRanges()
{
final List<TimeRange> timeRanges = timeRangeFactory.createTimeRanges("1w,27m , 2d,3h");
assertThat(timeRanges).hasSize(4);
assertThat(timeRanges.get(0).getDuration().toMillis()).isEqualTo(TimeUnit.MINUTES.toMillis(27));
assertThat(timeRanges.get(1).getDuration().toMillis()).isEqualTo(TimeUnit.HOURS.toMillis(3));
assertThat(timeRanges.get(2).getDuration().toMillis()).isEqualTo(TimeUnit.DAYS.toMillis(2));
assertThat(timeRanges.get(3).getDuration().toMillis()).isEqualTo(TimeUnit.DAYS.toMillis(7));
}
@Test
public void testCreateCommaSeparatedRangesWithWrongInput()
{
final List<TimeRange> timeRanges = timeRangeFactory.createTimeRanges("1w;w2,d,w.d2,3h");
assertThat(timeRanges).hasSize(1);
assertThat(timeRanges.get(0).getDuration().toMillis()).isEqualTo(TimeUnit.HOURS.toMillis(3));
}
@Test
public void testCreateOneMinute()
{
final TimeRange timeRange = timeRangeFactory.createTimeRange("1m");
assertThat(timeRange.getLabel()).isEqualTo(DefaultTimeRangeFactory.LABEL_PROCESSES_RANGE_MINUTE);
assertThat(timeRange.getDuration().toMillis()).isEqualTo(TimeUnit.MINUTES.toMillis(1));
}
@Test
public void testCreateManyMinutes()
{
final TimeRange timeRange = timeRangeFactory.createTimeRange("5m");
assertThat(timeRange.getLabel())
.isEqualTo(DefaultTimeRangeFactory.LABEL_PROCESSES_RANGE_MINUTE.concat(DefaultTimeRangeFactory.PLURAL_SUFFIX));
assertThat(timeRange.getDuration().toMillis()).isEqualTo(TimeUnit.MINUTES.toMillis(5));
}
@Test
public void testCreateOneDay()
{
final TimeRange timeRange = timeRangeFactory.createTimeRange("1d");
assertThat(timeRange.getLabel()).isEqualTo(DefaultTimeRangeFactory.LABEL_PROCESSES_RANGE_DAY);
assertThat(timeRange.getDuration().toMillis()).isEqualTo(TimeUnit.DAYS.toMillis(1));
}
@Test
public void testCreateManyDays()
{
final TimeRange timeRange = timeRangeFactory.createTimeRange("5d");
assertThat(timeRange.getLabel())
.isEqualTo(DefaultTimeRangeFactory.LABEL_PROCESSES_RANGE_DAY.concat(DefaultTimeRangeFactory.PLURAL_SUFFIX));
assertThat(timeRange.getDuration().toMillis()).isEqualTo(TimeUnit.DAYS.toMillis(5));
}
@Test
public void testCreateWrongInput()
{
assertThat(timeRangeFactory.createTimeRange("5d4d")).isNull();
assertThat(timeRangeFactory.createTimeRange("05")).isNull();
assertThat(timeRangeFactory.createTimeRange("5ww")).isNull();
assertThat(timeRangeFactory.createTimeRange("5hh")).isNull();
assertThat(timeRangeFactory.createTimeRange("5kd3")).isNull();
}
@Test
public void testCreateOneHour()
{
final TimeRange timeRange = timeRangeFactory.createTimeRange("1h");
assertThat(timeRange.getLabel()).isEqualTo(DefaultTimeRangeFactory.LABEL_PROCESSES_RANGE_HOUR);
assertThat(timeRange.getDuration().toMillis()).isEqualTo(TimeUnit.HOURS.toMillis(1));
}
@Test
public void testCreateManyHours()
{
final TimeRange timeRange = timeRangeFactory.createTimeRange("5h");
assertThat(timeRange.getLabel())
.isEqualTo(DefaultTimeRangeFactory.LABEL_PROCESSES_RANGE_HOUR.concat(DefaultTimeRangeFactory.PLURAL_SUFFIX));
assertThat(timeRange.getDuration().toMillis()).isEqualTo(TimeUnit.HOURS.toMillis(5));
}
@Test
public void testCreateOneWeek()
{
final TimeRange timeRange = timeRangeFactory.createTimeRange("1w");
assertThat(timeRange.getLabel()).isEqualTo(DefaultTimeRangeFactory.LABEL_PROCESSES_RANGE_WEEK);
assertThat(timeRange.getDuration().toMillis()).isEqualTo(TimeUnit.DAYS.toMillis(7));
}
@Test
public void testCreateManyWeeks()
{
final TimeRange timeRange = timeRangeFactory.createTimeRange("5w");
assertThat(timeRange.getLabel())
.isEqualTo(DefaultTimeRangeFactory.LABEL_PROCESSES_RANGE_WEEK.concat(DefaultTimeRangeFactory.PLURAL_SUFFIX));
assertThat(timeRange.getDuration().toMillis()).isEqualTo(TimeUnit.DAYS.toMillis(5 * 7));
}
} |
package com.estafet.jsf.converters;
import javax.el.ValueExpression;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import com.estafet.jsf.model.employees.Employee;
import com.estafet.jsf.model.employees.EmployeesView;
@FacesConverter(value = "employeeConverter")
public class EmployeeConverter implements Converter{
@Override
public Object getAsObject(FacesContext ctx, UIComponent uiComponent, String name) {
ValueExpression vex =
ctx.getApplication().getExpressionFactory()
.createValueExpression(ctx.getELContext(),
"#{employeesView}", EmployeesView.class);
EmployeesView employeeBean = (EmployeesView)vex.getValue(ctx.getELContext());
return employeeBean.getEmployee(name);
}
@Override
public String getAsString(FacesContext ctx, UIComponent uiComponent, Object employee) {
return ((Employee) employee).getName();
}
}
|
import java.util.HashMap;
public class Node
{
private String name;
private Boolean isStartNode;
private HashMap<Node, Integer> adjacentNodes;
private Boolean visited;
private Node parent;
private Integer cost;
/**
*
* @param name: String, name of the node as read-in from the input file
* @param isStart: Boolean, whether the node is the start of the map
*/
public Node(String name, Boolean isStart)
{
this.name = name;
this.isStartNode = isStart;
this.adjacentNodes = new HashMap<Node, Integer>();
this.visited = false;
this.parent = null;
this.cost = 0;
}
/**Getter for the node's name
*
* @return String, name member function
*/
public String getName()
{
return this.name;
}
/** Sets member variable visited to True
*
*/
public void visited()
{
this.visited = true;
}
/** Returns value of the member variable visited
*
* @return Boolean: True-Node has been visited before
* False-Node has not been visited
*/
public Boolean hasBeenVisited()
{
return this.visited;
}
/**Check if the node is the start node
*
* @return Boolean; true is node is start of map, otherwise false
*/
public Boolean isStartNode()
{
return this.isStartNode;
}
/** Sets the parent node, used in the solution reconstruction
* @param pNode, node that will be the parent node
*/
public void setParentNode(Node pNode)
{
this.parent = pNode;
}
/** Get the node's parent node
*
* @return Node corresponding to the parent node of this node
*/
public Node getParentNode()
{
return this.parent;
}
/** Add adjacent node to the node's map
*
* @param node: Node object
* @param cost: Cost of the edge
*/
public void addAdjacentNode(Node node, Integer cost)
{
this.adjacentNodes.put(node, cost);
}
/** Getter for the node's map of adjacent nodes
*
* @return HashMap<Node, Integer>, node's stored adjacent nodes
*/
public HashMap<Node, Integer> getAdjacentNodes()
{
return this.adjacentNodes;
}
/** Sets the cost to get to this node from the start node
* @param cost Integer value
*/
public void setCost(Integer cost)
{
this.cost = cost;
}
/** Get the cost to get to this node from the start node
*
*@return Integer, flight cost
*/
public Integer getCost()
{
return this.cost;
}
}; |
package com.yarg.animatronics.log;
public class Logger {
public static enum SEVERITY {
INFO("INFO"),
WARNING("WARNING"),
DEBUG("DEBUG"),
ERROR("ERROR");
private final String severity;
private SEVERITY(String severity) {
this.severity = severity;
}
public String getSeverityString() {
return severity;
}
}
/**
* Write a log entry if writeToLog is set to true. Allows for easy command line configuration of logging. All log
* entries are written to stdout.
* @param severity Severity of the log message.
* @param message Message to write to the log.
* @param writeToLog Message to write to the log.
*/
public static void log(SEVERITY severity, String message, boolean writeToLog) {
if (writeToLog) {
log(severity, message);
}
}
/**
* Write a log entry. All log entries are written to stdout.
* @param severity Severity of the log message.
* @param message Message to write to the log.
*/
public static void log(SEVERITY severity, String message) {
String logMessage = String.format("[%s] %s", severity.getSeverityString(), message);
System.out.println(logMessage);
}
}
|
package ejercicios.nonacces.finall;
public class EstudianteOdontologia extends EstudianteMedicina {
//Un est. de odontologia es un estudiante de medicina==SI
// Sobreescribiendo el metodo del padre
// NO se puede SOBREESCRIBIR un metodo final del padre
protected void realizarPracticas() {
System.out.println("Realiza 100 horas de prácticas");
}
// sobreescribiendo un metodo con la misma firma
protected void realizarPasantias() {
System.out.println("Realiza 200 horas de pasantías");
}
}
|
/******************************************************************************
*
* Copyright 2019 IBM Corporation and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package io.website;
public final class Constants {
// Kabanero
public static final String PRODUCT_VERSION = getEnv("PRODUCT_VERSION", "");
// Kabanero Instance
public static final String DEFAULT_USER_NAME = getEnv("USER_NAME", "");
public static final String DEFAULT_INSTANCE_NAME = getEnv("INSTANCE_NAME", "kabanero");
public static final String DEFAULT_DATE_CREATED = getEnv("DATE_CREATED", "");
public static final String DEFAULT_CLUSTER_NAME = getEnv("CLUSTER_NAME", "");
public static final String CLI_URL = getEnv("CLI_URL", "");
//OAuth
public static final String USER_API = getEnv("USER_API", null);
public static final String AUTHORIZATION_ENDPOINT = getEnv("AUTHORIZATION_ENDPOINT", null);
public static final String TOKEN_ENDPOINT = getEnv("TOKEN_ENDPOINT", null);
public static final String WEBSITE = getEnv("WEBSITE", null);
// Kabanero Tools
public static final String KAPPNAV_LABEL = "Application Navigator";
public static final String KAPPNAV_URL = getEnv("KAPPNAV_URL", "");
public static final String KAPPNAV_DESCRIPTION = "Manage your applications using Application Navigator";
public static final String KAPPNAV_ACTION_TEXT = "Manage Applications";
public static final String CODEREADY_LABEL = "Red Hat CodeReady Workspaces";
public static final String CODEREADY_URL = getEnv("CODEREADY_URL", "");
public static final String CODEREADY_DESCRIPTION = "Red Hat CodeReady Workspaces provides a consistent, secure, and zero-configuration development environment.";
public static final String CODEREADY_ACTION_TEXT = "Go to CodeReady";
// OKD
public static final String LANDING_URL = getEnv("LANDING_URL", "https://kabanero.io");
/*
title: The text label
icon: The icon you want to appear
url: where the go when this item is clicked
description: Short description
*/
public static final String FEATURED_APP_JS = String.join(
"",
"(function() {",
"window.OPENSHIFT_CONSTANTS.SAAS_OFFERINGS = [{",
"title: 'Kabanero',",
"icon: 'icon-kabanero-feature',",
"url: '" + Constants.LANDING_URL + "',",
"description: 'Get started with Kabanero.'",
"}];",
"}());"
);
/*
title: The text label
iconClass: The icon you want to appear
href: where the go when this item is clicked
tooltip: Optional tooltip to display on hover
*/
public static final String APP_LAUNCHER_JS = String.join(
"",
"(function() {",
"window.OPENSHIFT_CONSTANTS.APP_LAUNCHER_NAVIGATION = [{",
"title: 'Kabanero',",
"iconClass: 'icon-kabanero-launcher',",
"href: '" + Constants.LANDING_URL + "',",
"tooltip: 'Get started with Kabanero.'",
"}];",
"}());"
);
/*
title: The text label
iconClass: The icon you want to appear
href: where the go when this item is clicked
tooltip: Optional tooltip to display on hover
*/
public static final String APP_NAV_ICON_CSS = String.join(
"",
".icon-kabanero-launcher {",
"background-repeat: no-repeat;",
"background-image: url(" + Constants.LANDING_URL + "/img/favicon/favicon-16x16.png);",
"height: 16px;",
"width: 16px;",
"}",
".icon-kabanero-navigation {",
"background-repeat: no-repeat;",
"background-image: url(" + Constants.LANDING_URL + "/img/gray-kabanero-logo.png);",
"margin-right: 13px;",
"width: 18px;",
"background-size: contain;",
"}",
".icon-kabanero-feature {",
"display: block;",
"background-repeat: no-repeat;",
"background-image: url(" + Constants.LANDING_URL + "/img/Kabanero_logo_white.png);",
"height: 90px;",
"width: 60px;",
"}"
);
public static final String PROJECT_NAVIGATION_2_JS = String.join(
"",
"(function() {",
"window.OPENSHIFT_CONSTANTS.PROJECT_NAVIGATION.push({",
"label: 'Kabanero',",
"iconClass: 'icon-kabanero-navigation',",
"href: '" + Constants.LANDING_URL + "',",
"});",
"}());"
);
private static String getEnv(String envKey, String fallback){
String envValue = System.getenv(envKey);
return envValue == null ? fallback : envValue;
}
} |
package com.ibeiliao.pay.account.impl.service;
import com.google.common.collect.Lists;
import com.ibeiliao.pay.account.api.dto.BankVO;
import com.ibeiliao.pay.account.api.enums.BankStatus;
import com.ibeiliao.pay.account.impl.dao.BankDao;
import com.ibeiliao.pay.account.impl.entity.BankPO;
import com.ibeiliao.pay.common.utils.VOUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 银行相关业务实现类
* Created by jingyesi on 16/7/25.
*/
@Service
public class BankService {
private static final Logger logger = LoggerFactory.getLogger(BankService.class);
@Autowired
BankDao bankDao;
/**
* 获取所有的有效银行
* @return
*/
public List<BankVO> queryAllValidList(){
logger.info("service#BankService#queryAllValidList | | ");
List<BankPO> list = bankDao.queryAllValidList(BankStatus.VALID.getStatus());
List<BankVO> rs = Lists.newArrayList();
if(CollectionUtils.isNotEmpty(list)){
for(BankPO po : list){
BankVO vo = new BankVO();
VOUtil.copy(po, vo);
vo.setStatus(BankStatus.from(po.getStatus()));
rs.add(vo);
}
}
return rs;
}
}
|
package com.pfchoice.springboot.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.util.UriComponentsBuilder;
import com.pfchoice.springboot.model.AttPhysician;
import com.pfchoice.springboot.repositories.specifications.AttPhysicianSpecifications;
import com.pfchoice.springboot.service.AttPhysicianService;
import com.pfchoice.springboot.util.CustomErrorType;
@RestController
@RequestMapping("/api")
@SuppressWarnings({ "unchecked", "rawtypes" })
@SessionAttributes({ "username", "roleId", "userId", "roleName" })
public class AttPhysicianController {
public static final Logger logger = LoggerFactory.getLogger(AttPhysicianController.class);
@Autowired
AttPhysicianService attPhysicianService; // Service which will do all data
// retrieval/manipulation work
@Secured({ "ROLE_ADMIN", "ROLE_AGENT", "ROLE_EVENT_COORDINATOR", "ROLE_CARE_COORDINATOR", "ROLE_MANAGER" })
// -------------------Retrieve AttPhysicians as per page request
// ---------------------------------------------
@RequestMapping(value = "/attPhysician/", method = RequestMethod.GET)
public ResponseEntity<Page<AttPhysician>> listAllAttPhysicians(
@PageableDefault(page = 0, size = 100) Pageable pageRequest,
@RequestParam(value = "search", required = false) String search) {
Specification<AttPhysician> spec = new AttPhysicianSpecifications(search);
Page<AttPhysician> attPhysicians = attPhysicianService.findAllAttPhysiciansByPage(spec, pageRequest);
if (attPhysicians.getTotalElements() == 0) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
// You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<Page<AttPhysician>>(attPhysicians, HttpStatus.OK);
}
// -------------------Retrieve Single
// AttPhysician------------------------------------------
@Secured({ "ROLE_ADMIN", "ROLE_AGENT", "ROLE_EVENT_COORDINATOR", "ROLE_CARE_COORDINATOR", "ROLE_MANAGER" })
@RequestMapping(value = "/attPhysician/{id}", method = RequestMethod.GET)
public ResponseEntity<?> getAttPhysician(@PathVariable("id") int id) {
logger.info("Fetching AttPhysician with id {}", id);
AttPhysician attPhysician = attPhysicianService.findById(id);
if (attPhysician == null) {
logger.error("AttPhysician with id {} not found.", id);
return new ResponseEntity(new CustomErrorType("AttPhysician with id " + id + " not found"),
HttpStatus.NOT_FOUND);
}
return new ResponseEntity<AttPhysician>(attPhysician, HttpStatus.OK);
}
// -------------------Create a
// AttPhysician-------------------------------------------
@Secured({ "ROLE_ADMIN", "ROLE_MANAGER", "ROLE_CARE_COORDINATOR" })
@RequestMapping(value = "/attPhysician/", method = RequestMethod.POST)
public ResponseEntity<?> createAttPhysician(@RequestBody AttPhysician attPhysician, UriComponentsBuilder ucBuilder,
@ModelAttribute("username") String username) {
logger.info("Creating AttPhysician : {}", attPhysician);
if (attPhysicianService.isAttPhysicianExist(attPhysician)) {
logger.error("Unable to create. A AttPhysician with name {} already exist", attPhysician.getName());
return new ResponseEntity(
new CustomErrorType(
"Unable to create. A AttPhysician with name " + attPhysician.getName() + " already exist."),
HttpStatus.CONFLICT);
}
// logger.info(" attPhysician.getRoles().size() :{} ",
// attPhysician.getRoles().size());
attPhysician.setCreatedBy(username);
attPhysician.setUpdatedBy(username);
attPhysicianService.saveAttPhysician(attPhysician);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/api/attPhysician/{id}").buildAndExpand(attPhysician.getId()).toUri());
return new ResponseEntity<String>(headers, HttpStatus.CREATED);
}
// ------------------- Update a AttPhysician
// ------------------------------------------------
@Secured({ "ROLE_ADMIN", "ROLE_CARE_COORDINATOR", "ROLE_MANAGER" })
@RequestMapping(value = "/attPhysician/{id}", method = RequestMethod.PUT)
public ResponseEntity<?> updateAttPhysician(@PathVariable("id") int id, @RequestBody AttPhysician attPhysician,
@ModelAttribute("username") String username) {
logger.info("Updating AttPhysician with id {}", id);
AttPhysician currentAttPhysician = attPhysicianService.findById(id);
if (currentAttPhysician == null) {
logger.error("Unable to update. AttPhysician with id {} not found.", id);
return new ResponseEntity(
new CustomErrorType("Unable to upate. AttPhysician with id " + id + " not found."),
HttpStatus.NOT_FOUND);
}
currentAttPhysician.setName(attPhysician.getName());
currentAttPhysician.setCode(attPhysician.getCode());
currentAttPhysician.setUpdatedBy(username);
attPhysicianService.updateAttPhysician(currentAttPhysician);
return new ResponseEntity<AttPhysician>(currentAttPhysician, HttpStatus.OK);
}
// ------------------- Delete a
// AttPhysician-----------------------------------------
@Secured({ "ROLE_ADMIN" })
@RequestMapping(value = "/attPhysician/{id}", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteAttPhysician(@PathVariable("id") int id) {
logger.info("Fetching & Deleting AttPhysician with id {}", id);
AttPhysician attPhysician = attPhysicianService.findById(id);
if (attPhysician == null) {
logger.error("Unable to delete. AttPhysician with id {} not found.", id);
return new ResponseEntity(
new CustomErrorType("Unable to delete. AttPhysician with id " + id + " not found."),
HttpStatus.NOT_FOUND);
}
attPhysicianService.deleteAttPhysicianById(id);
return new ResponseEntity<AttPhysician>(HttpStatus.NO_CONTENT);
}
// ------------------- Delete All AttPhysicians-----------------------------
@Secured({ "ROLE_ADMIN" })
@RequestMapping(value = "/attPhysician/", method = RequestMethod.DELETE)
public ResponseEntity<AttPhysician> deleteAllAttPhysicians() {
logger.info("Deleting All AttPhysicians");
attPhysicianService.deleteAllAttPhysicians();
return new ResponseEntity<AttPhysician>(HttpStatus.NO_CONTENT);
}
} |
/*
* UniTime 3.5 (University Timetabling Application)
* Copyright (C) 2014, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.gwt.client.page;
import org.unitime.timetable.gwt.shared.MenuInterface.InfoInterface;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Composite;
/**
* @author Tomas Muller
*/
public class InfoPanel extends Composite implements InfoPanelDisplay {
private InfoPanelDisplay IMPL = GWT.create(InfoPanelDisplay.class);
private boolean iPreventDefault = false;
public InfoPanel() {
initWidget(IMPL.asWidget());
}
@Override
public String getText() {
return IMPL.getText();
}
@Override
public void setText(String text) {
IMPL.setText(text);
}
@Override
public String getHint() {
return IMPL.getHint();
}
@Override
public void setHint(String hint) {
IMPL.setHint(hint);
}
@Override
public void setUrl(String url) {
IMPL.setUrl(url);
}
@Override
public void setInfo(InfoInterface info) {
IMPL.setInfo(info);
}
@Override
public void setCallback(Callback callback) {
IMPL.setCallback(callback);
}
@Override
public boolean isPopupShowing() {
return IMPL.isPopupShowing();
}
@Override
public void setClickHandler(ClickHandler handler) {
IMPL.setClickHandler(handler);
}
@Override
public String getAriaLabel() {
return IMPL.getAriaLabel();
}
@Override
public void setAriaLabel(String text) {
IMPL.setAriaLabel(text);
}
public boolean isPreventDefault() { return iPreventDefault; }
public void setPreventDefault(boolean preventDefault) { iPreventDefault = preventDefault; }
}
|
package com.rs.game.player.dialogues;
public class JAGInformation extends Dialogue {
int npcId;
@Override
public void start() {
npcId = (Integer) parameters[0];
sendEntityDialogue(SEND_1_TEXT_CHAT,
new String[] {
"Account Guardian",
"Hello adventurer, how may I help you?" }, IS_NPC,
npcId, 9827);//first dialogue
}
@Override
public void run(int interfaceId, int componentId) {
if (stage == -1) {
stage = 0;
sendOptionsDialogue(SEND_DEFAULT_OPTIONS_TITLE,
"Who are you?", "What is JAG?", "I would like to "+(player.hasJAG ? "disable JAG." : "enable JAG."), "Nevermind.");
} else if (stage == 0) {
if (componentId == OPTION_1) {
stage = 1;
sendPlayerDialogue( 9827, "Who are you?" );
} else if (componentId == OPTION_2) {
stage = 2;
sendPlayerDialogue( 9827, "What is JAG?" );
} else if (componentId == OPTION_3) {
stage = 3;
sendPlayerDialogue( 9827, "I would like to "+(player.hasJAG ? "disable JAG." : "enable JAG."));
} else if (componentId == OPTION_4) {
stage = 120;
sendPlayerDialogue( 9827, "Erm, nevermind..");
} else if (stage == 120) {
end();
}
} else if (stage == 1) {
stage = -1;
sendEntityDialogue(SEND_1_TEXT_CHAT,
new String[] {
"Account Guardian",
"I am the Account Guardian, here to let players know about JAG." }, IS_NPC,
npcId, 9827);
} else if (stage == 2) {
stage = -1;
sendEntityDialogue(SEND_1_TEXT_CHAT,
new String[] {
"Account Guardian",
"JAG is a security measure added to make sure nobody is able to hijack your account." }, IS_NPC,
npcId, 9827);
} else if (stage == 3) {
if(player.hasJAG == true) {
stage = 8;
sendEntityDialogue(SEND_1_TEXT_CHAT,
new String[] {
"Account Guardian",
"Okay, just enter your random question and I will disable your JAG services." }, IS_NPC,
npcId, 9827);
} else {
stage = 4;
sendEntityDialogue(SEND_1_TEXT_CHAT,
new String[] {
"Account Guardian",
"Alright, but first you will need to set a question in case you need to register a new device." }, IS_NPC,
npcId, 9827);
}
} else if (stage == 4) {
stage = 5;
sendPlayerDialogue( 9827, "Erm.. okay, what's the question?" );
} else if (stage == 5) {
stage = 6;
sendOptionsDialogue(SEND_DEFAULT_OPTIONS_TITLE,
"What was your first pet's name?", "What is your favourite color?", "What is your mother's maiden name?");
} else if (stage == 6) {
if (componentId == OPTION_1) {
player.getTemporaryAttributtes().put("entering_jag1", Boolean.TRUE);
player.getPackets().sendInputNameScript("What was your first pet's name?");
} if (componentId == OPTION_2) {
player.getTemporaryAttributtes().put("entering_jag2", Boolean.TRUE);
player.getPackets().sendInputNameScript("What is your favourite color?");
} if (componentId == OPTION_3) {
player.getTemporaryAttributtes().put("entering_jag3", Boolean.TRUE);
player.getPackets().sendInputNameScript("What is your mother's maiden name?");
}
} else if (stage == 8) {
if(player.getJAG().randomQuestion == 1) {
player.getTemporaryAttributtes().put("removing_jag1", Boolean.TRUE);
player.getPackets().sendInputNameScript("What was your first pet's name?");
} else if(player.getJAG().randomQuestion == 2) {
player.getTemporaryAttributtes().put("removing_jag2", Boolean.TRUE);
player.getPackets().sendInputNameScript("What is your favourite color?");
} else if(player.getJAG().randomQuestion == 3) {
player.getTemporaryAttributtes().put("removing_jag3", Boolean.TRUE);
player.getPackets().sendInputNameScript("What is your mother's maiden name?");
}
} else {
end();
}
}
@Override
public void finish() {
}
} |
package com.tt.miniapp.launchschedule;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.ArrayMap;
import com.he.jsbinding.JsContext;
import com.he.jsbinding.JsScopedContext;
import com.storage.async.Action;
import com.storage.async.Scheduler;
import com.tt.c.a;
import com.tt.miniapp.AppConfig;
import com.tt.miniapp.AppbrandApplicationImpl;
import com.tt.miniapp.AppbrandServiceManager;
import com.tt.miniapp.JsRuntime;
import com.tt.miniapp.autotest.AutoTestManager;
import com.tt.miniapp.debug.DebugManager;
import com.tt.miniapp.dialog.LoadHelper;
import com.tt.miniapp.errorcode.ErrorCode;
import com.tt.miniapp.event.InnerEventHelper;
import com.tt.miniapp.event.LoadStateManager;
import com.tt.miniapp.jsbridge.JsRuntimeManager;
import com.tt.miniapp.launchcache.LaunchCacheDAO;
import com.tt.miniapp.launchcache.RequestType;
import com.tt.miniapp.launchcache.meta.AppInfoRequestListener;
import com.tt.miniapp.launchcache.meta.MetaService;
import com.tt.miniapp.launchcache.pkg.PkgService;
import com.tt.miniapp.launchcache.pkg.StreamDownloadInstallListener;
import com.tt.miniapp.manager.PreTTRequestManager;
import com.tt.miniapp.manager.SynHistoryManager;
import com.tt.miniapp.mvp.TTAppbrandPresenter;
import com.tt.miniapp.mvp.TTAppbrandView;
import com.tt.miniapp.net.httpdns.NetDnsResolver;
import com.tt.miniapp.preload.PreloadManager;
import com.tt.miniapp.route.RouteEventCtrl;
import com.tt.miniapp.storage.filestorge.FileManager;
import com.tt.miniapp.streamloader.LoadTask;
import com.tt.miniapp.streamloader.StreamLoader;
import com.tt.miniapp.thread.ThreadUtil;
import com.tt.miniapp.util.NetUtil;
import com.tt.miniapp.util.PageUtil;
import com.tt.miniapp.util.RenderSnapShotManager;
import com.tt.miniapp.util.TimeLogger;
import com.tt.miniapp.util.ToolUtils;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.AppbrandContext;
import com.tt.miniapphost.LaunchThreadPool;
import com.tt.miniapphost.entity.AppInfoEntity;
import com.tt.miniapphost.host.HostDependManager;
import com.tt.miniapphost.monitor.AppBrandMonitor;
import com.tt.miniapphost.util.ProcessUtil;
import com.tt.option.d;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import org.json.JSONObject;
public class LaunchScheduler extends AppbrandServiceManager.ServiceBase implements TTAppbrandView {
private d.b blockLoadingCallback = HostDependManager.getInst().createBlockLoadingCallback();
private boolean isAdSiteBrowser = false;
private final Object mBindViewLock = new Object();
private volatile boolean mIsSnapShotDomReady = false;
private boolean mJsCoreReady = false;
public LaunchProgress mLaunchProgress = new LaunchProgress();
private final Object mLoadLock = new Object();
private ArrayList<Runnable> mPendingRunnableList;
public TTAppbrandPresenter mPresenter = new TTAppbrandPresenter(this.mApp, this);
private int mProgress = -1;
public TTAppbrandView mRealView;
private volatile int mState = 0;
private AbsSubLaunchScheduler mSubScheduler;
private boolean mWebViewReady = false;
public LaunchScheduler(AppbrandApplicationImpl paramAppbrandApplicationImpl) {
super(paramAppbrandApplicationImpl);
}
private void asyncUpdateApp(final Context context, AppInfoEntity paramAppInfoEntity) {
final String currentAppLaunchFrom = paramAppInfoEntity.launchFrom;
final String currentAppScene = paramAppInfoEntity.scene;
final String currentAppSubScene = paramAppInfoEntity.subScene;
final String currentAppVersion = paramAppInfoEntity.version;
final long currentAppVersionCode = paramAppInfoEntity.versionCode;
((MetaService)this.mApp.getService(MetaService.class)).requestAsyncMeta(context, new AppInfoRequestListener() {
public void onAppInfoInvalid(AppInfoEntity param1AppInfoEntity, int param1Int) {
if (param1Int == 1)
LaunchScheduler.this.offline();
}
public void requestAppInfoFail(String param1String1, String param1String2) {
LaunchScheduler.this.onUpdateFailed();
}
public void requestAppInfoSuccess(AppInfoEntity param1AppInfoEntity) {
LaunchScheduler.this.prepareAsyncDownloadPkg(context, param1AppInfoEntity, currentAppVersion, currentAppVersionCode, currentAppLaunchFrom, currentAppScene, currentAppSubScene);
}
});
}
private boolean initAppConfig() {
AppConfig appConfig = this.mApp.initAppConfig();
if (appConfig == null) {
AppBrandLogger.e("LaunchScheduler", new Object[] { "parse appConfig error" });
InnerEventHelper.mpLoadResult(0L, "parse_app_config_fail", "parse appConfig fail", 0L, 0L, LoadStateManager.getIns().getLoadState());
((TimeLogger)this.mApp.getService(TimeLogger.class)).logTimeDuration(new String[] { "BaseActivityProxy_parseAppConfigFail" });
AppBrandMonitor.reportPreloadCase("initAppConfig_appConfig_null", 6010);
LoadHelper.handleMiniProcessFail(ErrorCode.MAIN.PARSE_APPCONFIG_ERROR.getCode());
return false;
}
AppInfoEntity appInfoEntity = this.mApp.getAppInfo();
if (appInfoEntity != null)
appInfoEntity.isLandScape = "landscape".equals(appConfig.screenOrientation);
initStartPage();
return true;
}
private void initInstallAppDir(AppInfoEntity paramAppInfoEntity) {
Application application = AppbrandContext.getInst().getApplicationContext();
LaunchCacheDAO.CacheVersionDir cacheVersionDir = LaunchCacheDAO.INSTANCE.getCacheAppIdDir((Context)application, paramAppInfoEntity.appId).getCacheVersionDir(paramAppInfoEntity.versionCode, RequestType.normal);
FileManager.inst().setCodeRootFilePath(cacheVersionDir.getInstallDir().getAbsolutePath());
}
private void initStartPage() {
AppInfoEntity appInfoEntity = this.mApp.getAppInfo();
if (appInfoEntity != null) {
String str = appInfoEntity.startPage;
if (!TextUtils.isEmpty(str)) {
AppBrandLogger.d("LaunchScheduler", new Object[] { "initStartPage ", str });
getNormalStartPage(str);
}
}
}
private void updateAppInfoOnAsyncUpdate(AppInfoEntity paramAppInfoEntity) {
AppInfoEntity appInfoEntity = this.mApp.getAppInfo();
appInfoEntity.encryptextra = paramAppInfoEntity.encryptextra;
appInfoEntity.ttBlackCode = paramAppInfoEntity.ttBlackCode;
appInfoEntity.ttSafeCode = paramAppInfoEntity.ttSafeCode;
appInfoEntity.shareLevel = paramAppInfoEntity.shareLevel;
appInfoEntity.state = paramAppInfoEntity.state;
appInfoEntity.versionState = paramAppInfoEntity.versionState;
appInfoEntity.domains = paramAppInfoEntity.domains;
appInfoEntity.adlist = paramAppInfoEntity.adlist;
appInfoEntity.libra_path = paramAppInfoEntity.libra_path;
this.mApp.setAppInfo(appInfoEntity);
}
public void bindView(TTAppbrandView paramTTAppbrandView) {
((TimeLogger)this.mApp.getService(TimeLogger.class)).logTimeDuration(new String[] { "LaunchScheduler_bindView" });
synchronized (this.mBindViewLock) {
this.mRealView = paramTTAppbrandView;
if (this.mPendingRunnableList != null) {
Iterator<Runnable> iterator = this.mPendingRunnableList.iterator();
while (iterator.hasNext())
((Runnable)iterator.next()).run();
this.mPendingRunnableList = null;
}
if (this.mProgress >= 0)
this.mRealView.miniAppDownloadInstallProgress(this.mProgress);
this.mBindViewLock.notifyAll();
return;
}
}
public ArrayMap<String, Long> getDurationForOpen() {
return this.mLaunchProgress.getDurationForOpen();
}
public int getLaunchProgress() {
return this.mLaunchProgress.getProgress();
}
public String getNormalStartPage(String paramString) {
if (!TextUtils.isEmpty(paramString)) {
AppInfoEntity appInfoEntity = this.mApp.getAppInfo();
String str = PageUtil.getCleanPath(paramString);
ArrayList arrayList = null;
AppConfig appConfig = this.mApp.getAppConfig();
if (appConfig != null)
arrayList = appConfig.getPageList();
if (arrayList != null && arrayList.size() > 0) {
if (arrayList.contains(str)) {
appInfoEntity.startPage = paramString;
} else {
appInfoEntity.startPage = appConfig.mEntryPath;
}
AppBrandLogger.d("LaunchScheduler", new Object[] { "getNormalStartPage ", appInfoEntity.startPage });
return appInfoEntity.startPage;
}
}
return "";
}
public boolean isAtLeastLaunching() {
return (this.mState > 0);
}
public void loadWhenInstallSuccess() {
synchronized (this.mLoadLock) {
if (this.mState != 3)
return;
this.mState = 4;
((TimeLogger)this.mApp.getService(TimeLogger.class)).logTimeDuration(new String[] { "LaunchScheduler_loadWhenInstallSuccess" });
((AutoTestManager)this.mApp.getService(AutoTestManager.class)).addEvent("stopDownloadInstallTime");
this.mApp.getLifeCycleManager().notifyMiniAppInstallSuccess();
null = this.mApp.getAppInfo();
if (!this.isAdSiteBrowser) {
if (!initAppConfig())
return;
this.mLaunchProgress.updateStatus(ILaunchStatus.STATUS_PKG_INSTALL_SUCCESS);
RouteEventCtrl routeEventCtrl = this.mApp.getRouteEventCtrl();
if (routeEventCtrl != null)
routeEventCtrl.setLaunchOption((AppInfoEntity)null, this.mApp.getAppConfig());
Application application = AppbrandContext.getInst().getApplicationContext();
AppConfig appConfig = this.mApp.getAppConfig();
String str = this.mApp.getSchema();
PreTTRequestManager.saveAndStartPrefetch((Context)application, appConfig, ((AppInfoEntity)null).appId, str);
}
NetUtil.registerListener();
this.mSubScheduler.onMiniAppInstallSuccess();
postAtViewReady(new Runnable() {
public void run() {
LaunchScheduler.this.mRealView.miniAppInstallSuccess();
}
});
if (!null.isLocalTest()) {
if (((AppInfoEntity)null).getFromType == 1) {
asyncUpdateApp((Context)AppbrandContext.getInst().getApplicationContext(), (AppInfoEntity)null);
return;
}
InnerEventHelper.mpVersionInfo(true, ((AppInfoEntity)null).version, ((AppInfoEntity)null).versionCode);
}
return;
}
}
public void metaExpired() {
waitForViewBound();
ThreadUtil.runOnUIThread(new Runnable() {
public void run() {
LaunchScheduler.this.mRealView.metaExpired();
}
});
}
public void miniAppDownloadInstallFail(String paramString1, String paramString2) {
((TimeLogger)this.mApp.getService(TimeLogger.class)).logError(new String[] { "LaunchScheduler_miniAppDownloadInstallFail" });
waitForViewBound();
this.mRealView.miniAppDownloadInstallFail(paramString1, paramString2);
}
public void miniAppDownloadInstallProgress(int paramInt) {
this.mProgress = paramInt;
TTAppbrandView tTAppbrandView = this.mRealView;
if (tTAppbrandView != null)
tTAppbrandView.miniAppDownloadInstallProgress(paramInt);
}
public void miniAppInstallSuccess() {
((TimeLogger)this.mApp.getService(TimeLogger.class)).logTimeDuration(new String[] { "miniAppInstallSuccess" });
this.mState = 3;
if (!((RenderSnapShotManager)this.mApp.getService(RenderSnapShotManager.class)).isSnapShotRender()) {
loadWhenInstallSuccess();
return;
}
if (this.mIsSnapShotDomReady)
loadWhenInstallSuccess();
}
public void mismatchHost() {
waitForViewBound();
ThreadUtil.runOnUIThread(new Runnable() {
public void run() {
LaunchScheduler.this.mRealView.mismatchHost();
}
});
}
public void noPermission() {
waitForViewBound();
ThreadUtil.runOnUIThread(new Runnable() {
public void run() {
LaunchScheduler.this.mRealView.noPermission();
}
});
}
public void offline() {
waitForViewBound();
ThreadUtil.runOnUIThread(new Runnable() {
public void run() {
LaunchScheduler.this.mRealView.offline();
}
});
}
public void onCheckForUpdate(AppInfoEntity paramAppInfoEntity) {
AppBrandLogger.i("LaunchScheduler", new Object[] { "onCheckForUpdate" });
try {
if (!this.isAdSiteBrowser) {
boolean bool;
AppInfoEntity appInfoEntity = this.mApp.getAppInfo();
JSONObject jSONObject = new JSONObject();
if (appInfoEntity.versionCode < paramAppInfoEntity.versionCode) {
bool = true;
} else {
bool = false;
}
jSONObject.put("hasUpdate", bool);
this.mApp.getJsBridge().sendMsgToJsCore("onCheckForUpdate", jSONObject.toString());
}
updateAppInfoOnAsyncUpdate(paramAppInfoEntity);
return;
} catch (Exception exception) {
AppBrandLogger.e("onCheckForUpdate", new Object[] { exception });
return;
}
}
public void onDOMReady() {
this.mLaunchProgress.updateStatus(ILaunchStatus.STATUS_LOAD_ENTRY_PAGE_SUCCESS);
((PreloadManager)this.mApp.getService(PreloadManager.class)).preloadOnIdle();
this.mApp.notifyPreloadEmptyProcess();
postAtViewReady(new Runnable() {
public void run() {
LaunchScheduler.this.mRealView.onDOMReady();
((TimeLogger)LaunchScheduler.this.mApp.getService(TimeLogger.class)).stopScheduleFlush();
}
});
}
public void onDestroy() {
AppBrandLogger.i("LaunchScheduler", new Object[] { "onDestroy" });
LoadTask loadTask = StreamLoader.getLoadTask();
if (loadTask != null)
loadTask.release();
}
public void onEnvironmentReady() {
((TimeLogger)this.mApp.getService(TimeLogger.class)).logTimeDuration(new String[] { "LaunchScheduler_onEnvironmentReady" });
((RenderSnapShotManager)this.mApp.getService(RenderSnapShotManager.class)).onLoadResultSuccess();
a a = HostDependManager.getInst().getMiniAppLifeCycleInstance();
if (a != null)
a.a = true;
postAtViewReady(new Runnable() {
public void run() {
LaunchScheduler.this.mRealView.onEnvironmentReady();
}
});
}
public void onFirstContentfulPaint(final long adjustTimeDiff) {
this.mLaunchProgress.updateStatus(ILaunchStatus.STATUS_FIRST_PAGE_RENDER_SUCCESS, adjustTimeDiff);
postAtViewReady(new Runnable() {
public void run() {
LaunchScheduler.this.mRealView.onFirstContentfulPaint(adjustTimeDiff);
}
});
}
public void onFirstPaint() {
this.mApp.notifyPreloadEmptyProcess();
}
public void onJsCoreLoaded(int paramInt) {
if (paramInt == 1) {
this.mLaunchProgress.updateStatus(ILaunchStatus.STATUS_LOAD_TMA_CORE_SUCCESS);
return;
}
if (paramInt == 2)
this.mLaunchProgress.updateStatus(ILaunchStatus.STATUS_LOAD_TMG_CORE_SUCCESS);
}
void onJsCoreReady() {
if (this.mJsCoreReady)
return;
synchronized (this.mLoadLock) {
if (this.mJsCoreReady)
return;
((TimeLogger)this.mApp.getService(TimeLogger.class)).logTimeDuration(new String[] { "LaunchScheduler_onJsCoreReady" });
this.mJsCoreReady = true;
if (this.mWebViewReady)
onEnvironmentReady();
this.mApp.getRouteEventCtrl().onJsCoreReady();
this.mLaunchProgress.updateStatus(ILaunchStatus.STATUS_LOAD_MAIN_JS_SUCCESS);
return;
}
}
public void onRemoteDebugOpen() {
waitForViewBound();
this.mRealView.onRemoteDebugOpen();
}
public void onRenderProcessGone(Boolean paramBoolean) {
if (isAtLeastLaunching()) {
postAtViewReady(new Runnable() {
public void run() {
LoadHelper.handleMiniProcessFail(ErrorCode.WEBVIEW.ON_RENDER_PROCESS_GONE.getCode());
}
});
return;
}
if (paramBoolean == null) {
LoadHelper.monitorErrorEvent(ErrorCode.WEBVIEW.ON_RENDER_PROCESS_GONE.getCode(), ErrorCode.WEBVIEW.ON_RENDER_PROCESS_GONE.getDesc());
} else {
String str = ErrorCode.WEBVIEW.ON_RENDER_PROCESS_GONE.getCode();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(ErrorCode.WEBVIEW.ON_RENDER_PROCESS_GONE.getDesc());
stringBuilder.append(", didCrash: ");
stringBuilder.append(paramBoolean);
LoadHelper.monitorErrorEvent(str, stringBuilder.toString());
}
ProcessUtil.killCurrentMiniAppProcess((Context)AppbrandContext.getInst().getApplicationContext());
}
public void onSnapShotDOMReady() {
((PreloadManager)this.mApp.getService(PreloadManager.class)).preloadOnIdle();
this.mIsSnapShotDomReady = true;
ThreadUtil.runOnWorkThread(new Action() {
public void act() {
LaunchScheduler.this.loadWhenInstallSuccess();
}
}, (Scheduler)LaunchThreadPool.getInst());
postAtViewReady(new Runnable() {
public void run() {
LaunchScheduler.this.mRealView.onSnapShotDOMReady();
}
});
}
public void onTemplateLoaded() {
this.mLaunchProgress.updateStatus(ILaunchStatus.STATUS_LOAD_TMPLATE_HTML_SUCCESS);
}
public void onUpdateFailed() {
AppBrandLogger.i("LaunchScheduler", new Object[] { "onUpdateFailed" });
if (!this.isAdSiteBrowser)
try {
this.mApp.getJsBridge().sendMsgToJsCore("onUpdateFailed", (new JSONObject()).toString());
return;
} catch (Exception exception) {
AppBrandLogger.e("onCheckForUpdate", new Object[] { exception });
}
}
public void onUpdateReady() {
AppBrandLogger.i("LaunchScheduler", new Object[] { "onUpdateReady" });
if (!this.isAdSiteBrowser)
try {
this.mApp.getJsBridge().sendMsgToJsCore("onUpdateReady", (new JSONObject()).toString());
return;
} catch (Exception exception) {
AppBrandLogger.e("onCheckForUpdate", new Object[] { exception });
}
}
public void onWebViewReady() {
if (this.mWebViewReady)
return;
synchronized (this.mLoadLock) {
if (this.mWebViewReady)
return;
((TimeLogger)this.mApp.getService(TimeLogger.class)).logTimeDuration(new String[] { "LaunchScheduler_onWebViewReady" });
this.mWebViewReady = true;
if (this.mJsCoreReady)
onEnvironmentReady();
this.mLaunchProgress.updateStatus(ILaunchStatus.STATUS_LOAD_PAGE_FRAME_JS_SUCCESS);
return;
}
}
public void postAtViewReady(Runnable paramRunnable) {
synchronized (this.mBindViewLock) {
if (this.mRealView != null) {
paramRunnable.run();
} else {
if (this.mPendingRunnableList == null)
this.mPendingRunnableList = new ArrayList<Runnable>();
this.mPendingRunnableList.add(paramRunnable);
}
return;
}
}
public void prepareAsyncDownloadPkg(Context paramContext, final AppInfoEntity appInfo, final String currentAppVersion, long paramLong, String paramString2, String paramString3, String paramString4) {
if (TextUtils.isEmpty(appInfo.version))
appInfo.version = currentAppVersion;
InnerEventHelper.mpVersionInfo(TextUtils.equals(currentAppVersion, appInfo.version), currentAppVersion, paramLong);
onCheckForUpdate(appInfo);
this.mApp.setUpdateAppInfo(appInfo);
if (appInfo.versionCode > paramLong) {
appInfo.launchFrom = paramString2;
appInfo.scene = paramString3;
appInfo.subScene = paramString4;
((PkgService)this.mApp.getService(PkgService.class)).downloadAsync(paramContext, appInfo, new StreamDownloadInstallListener() {
public void onDownloadSuccess(File param1File, boolean param1Boolean) {
AppBrandLogger.d("LaunchScheduler", new Object[] { "onInstallSuccess", Boolean.valueOf(param1Boolean) });
LaunchScheduler.this.onUpdateReady();
InnerEventHelper.mpAsyncNotify(appInfo.version, currentAppVersion);
}
public void onDownloadingProgress(int param1Int, long param1Long) {}
public void onFail(String param1String1, String param1String2) {
LaunchScheduler.this.onUpdateFailed();
}
public void onInstallSuccess() {}
public void onStop() {}
});
}
}
public void requestAppInfoFail(String paramString1, String paramString2) {
waitForViewBound();
this.mRealView.requestAppInfoFail(paramString1, paramString2);
}
public void requestAppInfoSuccess(final AppInfoEntity appInfo) {
((AutoTestManager)this.mApp.getService(AutoTestManager.class)).addEvent("stopRequestMeta");
((TimeLogger)this.mApp.getService(TimeLogger.class)).logTimeDuration(new String[] { "LaunchScheduler_requestAppInfoSuccess" });
((MetaService)this.mApp.getService(MetaService.class)).updateAppInfoAfterRequest(appInfo);
((AutoTestManager)this.mApp.getService(AutoTestManager.class)).addEventWithValue("appId", appInfo.appId);
((TimeLogger)this.mApp.getService(TimeLogger.class)).logTimeDuration(new String[] { "LaunchScheduler_AppInfoUpdatedAfterRequest" });
if (!appInfo.isWebApp())
initInstallAppDir(appInfo);
if (!this.isAdSiteBrowser) {
DebugManager.getInst().openDebug(new DebugManager.DebugCallback() {
public void complete() {
if ((DebugManager.getInst()).mIsRemoteDebug)
LaunchScheduler.this.onRemoteDebugOpen();
JsRuntime jsRuntime = ((JsRuntimeManager)LaunchScheduler.this.mApp.getService(JsRuntimeManager.class)).getCurrentRuntime();
if (LaunchScheduler.this.mApp.getAppInfo().isGame() && (jsRuntime == null || jsRuntime instanceof com.tt.miniapp.jsbridge.JsTMARuntime))
LaunchScheduler.this.waitForViewBound();
if (LaunchScheduler.this.mApp.getAppInfo().isGame())
((JsRuntimeManager)LaunchScheduler.this.mApp.getService(JsRuntimeManager.class)).getCurrentRuntime().executeInJsThread(new JsContext.ScopeCallback() {
public void run(JsScopedContext param2JsScopedContext) {
try {
((TimeLogger)LaunchScheduler.this.mApp.getService(TimeLogger.class)).logTimeDuration(new String[] { "LaunchScheduler_beforeMetaReady" });
param2JsScopedContext.eval("metaReady();", "metaReady");
((TimeLogger)LaunchScheduler.this.mApp.getService(TimeLogger.class)).logTimeDuration(new String[] { "LaunchScheduler_afterMetaReady" });
return;
} catch (Exception exception) {
AppBrandLogger.eWithThrowable("LaunchScheduler", "Call metaReady error.", exception);
return;
}
}
});
LaunchScheduler.this.mLaunchProgress.updateStatus(ILaunchStatus.STATUS_META_SUCCESS);
LaunchScheduler.this.postAtViewReady(new Runnable() {
public void run() {
LaunchScheduler.this.mRealView.requestAppInfoSuccess(appInfo);
}
});
if (!appInfo.isWebApp()) {
((AutoTestManager)LaunchScheduler.this.mApp.getService(AutoTestManager.class)).addEvent("startDownloadInstallTime");
LaunchScheduler.this.mPresenter.downloadInstallMiniApp((Context)AppbrandContext.getInst().getApplicationContext(), appInfo);
LoadStateManager.getIns().setLoadState("pkg_downloading");
}
}
});
} else {
this.mLaunchProgress.updateStatus(ILaunchStatus.STATUS_META_SUCCESS);
postAtViewReady(new Runnable() {
public void run() {
LaunchScheduler.this.mRealView.requestAppInfoSuccess(appInfo);
}
});
if (!appInfo.isWebApp()) {
this.mPresenter.downloadInstallMiniApp((Context)AppbrandContext.getInst().getApplicationContext(), appInfo);
LoadStateManager.getIns().setLoadState("pkg_downloading");
}
}
SynHistoryManager.getInstance().addToRecentApps(appInfo);
NetDnsResolver.getInst().preResolveInetAddressFromHttpDns(appInfo);
}
public void setAllCompleteProgress() {
for (int i = ILaunchStatus.STATUS_INIT; i < ILaunchStatus.STATUS_FIRST_PAGE_RENDER_SUCCESS; i++)
this.mLaunchProgress.updateStatus(i);
}
public void showNotSupportView() {
waitForViewBound();
ThreadUtil.runOnUIThread(new Runnable() {
public void run() {
LaunchScheduler.this.mRealView.showNotSupportView();
}
});
}
public void startLaunch(AppInfoEntity paramAppInfoEntity, String paramString1, String paramString2, Bundle paramBundle) {
// Byte code:
// 0: aload_0
// 1: monitorenter
// 2: aload_0
// 3: getfield mState : I
// 6: istore #5
// 8: iload #5
// 10: ifle -> 16
// 13: aload_0
// 14: monitorexit
// 15: return
// 16: aload_0
// 17: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 20: ldc com/tt/miniapp/util/TimeLogger
// 22: invokevirtual getService : (Ljava/lang/Class;)Lcom/tt/miniapp/AppbrandServiceManager$ServiceBase;
// 25: checkcast com/tt/miniapp/util/TimeLogger
// 28: iconst_1
// 29: anewarray java/lang/String
// 32: dup
// 33: iconst_0
// 34: ldc_w 'LaunchScheduler_startLaunch'
// 37: aastore
// 38: invokevirtual logTimeDuration : ([Ljava/lang/String;)V
// 41: aload_0
// 42: iconst_1
// 43: putfield mState : I
// 46: aload_0
// 47: invokestatic getInstance : ()Lcom/tt/miniapp/adsite/AdSiteManager;
// 50: aload_0
// 51: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 54: invokevirtual getMiniAppContext : ()Lcom/tt/miniapp/base/MiniAppContextWrapper;
// 57: invokevirtual getApplicationContext : ()Landroid/content/Context;
// 60: aload_1
// 61: invokevirtual initIsAdSiteBrowser : (Landroid/content/Context;Lcom/tt/miniapphost/entity/AppInfoEntity;)Z
// 64: putfield isAdSiteBrowser : Z
// 67: aload_0
// 68: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 71: aload_1
// 72: invokevirtual setAppInfo : (Lcom/tt/miniapphost/entity/AppInfoEntity;)V
// 75: invokestatic getInst : ()Lcom/tt/miniapphost/AppbrandContext;
// 78: aload_1
// 79: invokevirtual isGame : ()Z
// 82: invokevirtual setGame : (Z)V
// 85: aload_0
// 86: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 89: aload_2
// 90: invokevirtual setSchema : (Ljava/lang/String;)V
// 93: aload_0
// 94: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 97: ldc com/tt/miniapp/util/TimeLogger
// 99: invokevirtual getService : (Ljava/lang/Class;)Lcom/tt/miniapp/AppbrandServiceManager$ServiceBase;
// 102: checkcast com/tt/miniapp/util/TimeLogger
// 105: invokevirtual scheduleFlush : ()V
// 108: aload_3
// 109: ifnull -> 130
// 112: aload_0
// 113: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 116: ldc_w com/tt/miniapp/util/RenderSnapShotManager
// 119: invokevirtual getService : (Ljava/lang/Class;)Lcom/tt/miniapp/AppbrandServiceManager$ServiceBase;
// 122: checkcast com/tt/miniapp/util/RenderSnapShotManager
// 125: aload_3
// 126: aload_1
// 127: invokevirtual preHandleVDomData : (Ljava/lang/String;Lcom/tt/miniapphost/entity/AppInfoEntity;)V
// 130: invokestatic getInst : ()Lcom/tt/miniapphost/AppbrandContext;
// 133: invokevirtual getApplicationContext : ()Landroid/app/Application;
// 136: aload_2
// 137: invokestatic startPrefetch : (Landroid/content/Context;Ljava/lang/String;)V
// 140: aload #4
// 142: ifnull -> 241
// 145: aload #4
// 147: ldc_w 'lang'
// 150: invokevirtual getString : (Ljava/lang/String;)Ljava/lang/String;
// 153: astore_3
// 154: aload_3
// 155: ifnull -> 170
// 158: aload_3
// 159: invokestatic string2Locale : (Ljava/lang/String;)Ljava/util/Locale;
// 162: astore_3
// 163: invokestatic getInst : ()Lcom/tt/miniapphost/language/LocaleManager;
// 166: aload_3
// 167: invokevirtual notifyLangChange : (Ljava/util/Locale;)V
// 170: aload #4
// 172: ldc_w 'mp_open_app_schema_timestamp'
// 175: ldc2_w -1
// 178: invokevirtual getLong : (Ljava/lang/String;J)J
// 181: lstore #6
// 183: lload #6
// 185: lconst_0
// 186: lcmp
// 187: ifle -> 212
// 190: aload_0
// 191: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 194: ldc_w com/tt/miniapp/debug/PerformanceService
// 197: invokevirtual getService : (Ljava/lang/Class;)Lcom/tt/miniapp/AppbrandServiceManager$ServiceBase;
// 200: checkcast com/tt/miniapp/debug/PerformanceService
// 203: ldc_w 'clickApp'
// 206: lload #6
// 208: invokevirtual createPerformanceTimingObj : (Ljava/lang/String;J)Lcom/tt/miniapp/debug/PerformanceService$PerformanceTimingObj;
// 211: pop
// 212: aload #4
// 214: ldc_w 'mp_open_app_schema_cputime'
// 217: ldc2_w -1
// 220: invokevirtual getLong : (Ljava/lang/String;J)J
// 223: lstore #6
// 225: lload #6
// 227: lconst_0
// 228: lcmp
// 229: ifle -> 241
// 232: aload_0
// 233: getfield mLaunchProgress : Lcom/tt/miniapp/launchschedule/LaunchProgress;
// 236: lload #6
// 238: invokevirtual setOpenSchemaTime : (J)V
// 241: aload_0
// 242: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 245: ldc_w com/tt/miniapp/LifeCycleManager
// 248: invokevirtual getService : (Ljava/lang/Class;)Lcom/tt/miniapp/AppbrandServiceManager$ServiceBase;
// 251: checkcast com/tt/miniapp/LifeCycleManager
// 254: invokevirtual notifyAppStartLaunching : ()V
// 257: aload_0
// 258: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 261: invokevirtual getRouteEventCtrl : ()Lcom/tt/miniapp/route/RouteEventCtrl;
// 264: astore_3
// 265: aload_3
// 266: ifnull -> 273
// 269: aload_3
// 270: invokevirtual onAppLaunch : ()V
// 273: invokestatic getInst : ()Lcom/tt/miniapp/debug/DebugManager;
// 276: aload_1
// 277: invokevirtual initRemoteDebugInfo : (Lcom/tt/miniapphost/entity/AppInfoEntity;)V
// 280: aload_0
// 281: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 284: invokevirtual getLifeCycleManager : ()Lcom/tt/miniapp/LifeCycleManager;
// 287: aload_1
// 288: invokevirtual notifyAppInfoInited : (Lcom/tt/miniapphost/entity/AppInfoEntity;)V
// 291: aload_1
// 292: invokevirtual isGame : ()Z
// 295: ifne -> 343
// 298: aload_0
// 299: getfield isAdSiteBrowser : Z
// 302: ifeq -> 324
// 305: aload_0
// 306: new com/tt/miniapp/launchschedule/AdSiteLaunchScheduler
// 309: dup
// 310: aload_0
// 311: aload_0
// 312: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 315: invokespecial <init> : (Lcom/tt/miniapp/launchschedule/LaunchScheduler;Lcom/tt/miniapp/AppbrandApplicationImpl;)V
// 318: putfield mSubScheduler : Lcom/tt/miniapp/launchschedule/AbsSubLaunchScheduler;
// 321: goto -> 359
// 324: aload_0
// 325: new com/tt/miniapp/launchschedule/TMALaunchScheduler
// 328: dup
// 329: aload_0
// 330: aload_0
// 331: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 334: invokespecial <init> : (Lcom/tt/miniapp/launchschedule/LaunchScheduler;Lcom/tt/miniapp/AppbrandApplicationImpl;)V
// 337: putfield mSubScheduler : Lcom/tt/miniapp/launchschedule/AbsSubLaunchScheduler;
// 340: goto -> 359
// 343: aload_0
// 344: new com/tt/miniapp/launchschedule/TMGLaunchScheduler
// 347: dup
// 348: aload_0
// 349: aload_0
// 350: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 353: invokespecial <init> : (Lcom/tt/miniapp/launchschedule/LaunchScheduler;Lcom/tt/miniapp/AppbrandApplicationImpl;)V
// 356: putfield mSubScheduler : Lcom/tt/miniapp/launchschedule/AbsSubLaunchScheduler;
// 359: aload_0
// 360: getfield mSubScheduler : Lcom/tt/miniapp/launchschedule/AbsSubLaunchScheduler;
// 363: invokevirtual onStartLaunch : ()V
// 366: new com/tt/miniapp/launchschedule/LaunchScheduler$1
// 369: dup
// 370: aload_0
// 371: aload_2
// 372: invokespecial <init> : (Lcom/tt/miniapp/launchschedule/LaunchScheduler;Ljava/lang/String;)V
// 375: invokestatic getInst : ()Lcom/tt/miniapphost/LaunchThreadPool;
// 378: invokestatic runOnWorkThread : (Lcom/storage/async/Action;Lcom/storage/async/Scheduler;)V
// 381: aload_0
// 382: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 385: ldc com/tt/miniapp/util/TimeLogger
// 387: invokevirtual getService : (Ljava/lang/Class;)Lcom/tt/miniapp/AppbrandServiceManager$ServiceBase;
// 390: checkcast com/tt/miniapp/util/TimeLogger
// 393: iconst_1
// 394: anewarray java/lang/String
// 397: dup
// 398: iconst_0
// 399: ldc_w 'LaunchScheduler_startRequestAppInfo'
// 402: aastore
// 403: invokevirtual logTimeDuration : ([Ljava/lang/String;)V
// 406: invokestatic getIns : ()Lcom/tt/miniapp/event/LoadStateManager;
// 409: ldc_w 'meta_requesting'
// 412: invokevirtual setLoadState : (Ljava/lang/String;)V
// 415: new com/tt/miniapp/launchschedule/LaunchScheduler$2
// 418: dup
// 419: aload_0
// 420: aload_1
// 421: invokespecial <init> : (Lcom/tt/miniapp/launchschedule/LaunchScheduler;Lcom/tt/miniapphost/entity/AppInfoEntity;)V
// 424: pop
// 425: aload_0
// 426: getfield mApp : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 429: ldc_w com/tt/miniapp/autotest/AutoTestManager
// 432: invokevirtual getService : (Ljava/lang/Class;)Lcom/tt/miniapp/AppbrandServiceManager$ServiceBase;
// 435: checkcast com/tt/miniapp/autotest/AutoTestManager
// 438: ldc_w 'startRequestMeta'
// 441: invokevirtual addEvent : (Ljava/lang/String;)V
// 444: aload_0
// 445: getfield mPresenter : Lcom/tt/miniapp/mvp/TTAppbrandPresenter;
// 448: aload_1
// 449: invokevirtual requestAppInfo : (Lcom/tt/miniapphost/entity/AppInfoEntity;)V
// 452: aload_0
// 453: iconst_2
// 454: putfield mState : I
// 457: aload_0
// 458: monitorexit
// 459: return
// 460: astore_1
// 461: aload_0
// 462: monitorexit
// 463: aload_1
// 464: athrow
// Exception table:
// from to target type
// 2 8 460 finally
// 16 108 460 finally
// 112 130 460 finally
// 130 140 460 finally
// 145 154 460 finally
// 158 170 460 finally
// 170 183 460 finally
// 190 212 460 finally
// 212 225 460 finally
// 232 241 460 finally
// 241 265 460 finally
// 269 273 460 finally
// 273 321 460 finally
// 324 340 460 finally
// 343 359 460 finally
// 359 457 460 finally
}
public void startListenLaunchStatus(ILaunchProgressListener paramILaunchProgressListener) {
this.mLaunchProgress.start(paramILaunchProgressListener);
}
public void stopListenLaunchStatus() {
this.mLaunchProgress.stop();
}
public void waitForViewBound() {
// Byte code:
// 0: aload_0
// 1: getfield mRealView : Lcom/tt/miniapp/mvp/TTAppbrandView;
// 4: ifnonnull -> 41
// 7: aload_0
// 8: getfield mBindViewLock : Ljava/lang/Object;
// 11: astore_1
// 12: aload_1
// 13: monitorenter
// 14: aload_0
// 15: getfield mRealView : Lcom/tt/miniapp/mvp/TTAppbrandView;
// 18: astore_2
// 19: aload_2
// 20: ifnonnull -> 33
// 23: aload_0
// 24: getfield mBindViewLock : Ljava/lang/Object;
// 27: invokevirtual wait : ()V
// 30: goto -> 14
// 33: aload_1
// 34: monitorexit
// 35: return
// 36: astore_2
// 37: aload_1
// 38: monitorexit
// 39: aload_2
// 40: athrow
// 41: return
// 42: astore_2
// 43: goto -> 14
// Exception table:
// from to target type
// 14 19 36 finally
// 23 30 42 java/lang/InterruptedException
// 23 30 36 finally
// 33 35 36 finally
// 37 39 36 finally
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\launchschedule\LaunchScheduler.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package info.ntek.gsp.data.time;
/**
* Type of Day.
*
* @author Milos Milanovic
*/
public enum DayType {
RADNI_DAN(0),
SUBOTA(1),
NEDELJA(2);
private int mValue = 0;
DayType(int value) {
this.mValue = value;
}
public int getValue() {
return mValue;
}
public static String fromValue(DayType value) {
switch (value) {
case RADNI_DAN: {
return "R";
}
case SUBOTA: {
return "S";
}
case NEDELJA: {
return "N";
}
}
return null;
}
}
|
package com.args.cineduniya;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
public class forgot_password_activity extends AppCompatActivity {
EditText email;
Button forgot_btn;
TextView login;
FirebaseAuth mfirebaseAuth;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password_activity);
email = findViewById(R.id.forgot_email);
forgot_btn = findViewById(R.id.forgot_button);
login = findViewById(R.id.login_forgot);
progressBar = findViewById(R.id.progress_forgot);
mfirebaseAuth= FirebaseAuth.getInstance();
progressBar.setVisibility(View.GONE);
forgot_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email_id = email.getText().toString();
progressBar.setVisibility(View.VISIBLE);
if(email_id.isEmpty()){
progressBar.setVisibility(View.GONE);
email.setError("email is required");
email.requestFocus();
}
else if (!(email_id.isEmpty())){
mfirebaseAuth.sendPasswordResetEmail(email_id).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
email.setText("");
Toast.makeText(forgot_password_activity.this, "password reset link sent to your email", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
else
{
Toast.makeText(forgot_password_activity.this, "Account not found", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
}
});
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent login = new Intent(forgot_password_activity.this, Login_activity.class);
startActivity(login);
finish();
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
|
package com.lukian.creditmicroservice.dto;
import lombok.*;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString
public class ProductDTO {
private String name;
private int value;
}
|
package com.xncoding.jwt;
import com.xncoding.jwt.util.JWTUtil;
import com.xncoding.jwt.shiro.ShiroKit;
import org.junit.Test;
/**
* SimpleTest
*
* @author XiongNeng
* @version 1.0
* @since 2018/1/4
*/
public class SimpleTest {
@Test
public void testJwt() {
// 用户名
String username = "admin";
// 随机数
String salt = ShiroKit.getRandomSalt(16);
// 原密码
String password = "12345678";
System.out.println("输入密码: " + password);
System.out.println("随机数salt: " + salt);
// 需要存储这个salt??
String encodedPassword = ShiroKit.md5(password, username + salt);
System.out.println("加密后的密码: " + encodedPassword);
// 生成token
String token = JWTUtil.sign(username, encodedPassword);
System.out.println("生成Token: " + token);
// 验证token
boolean isVerified = JWTUtil.verify(token, username, encodedPassword);
System.out.println("是否验证通过" + isVerified);
}
}
|
package com.example.didiorder.activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
import com.example.didiorder.BaseActivity;
import com.example.didiorder.R;
import com.example.didiorder.bean.User;
import com.example.didiorder.presenter.UserActivityPresenter;
import com.example.didiorder.view.IUserActivityView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gc.materialdesign.views.ButtonFlat;
import com.gc.materialdesign.views.ButtonRectangle;
import com.weiwangcn.betterspinner.library.BetterSpinner;
import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobUser;
/**
* Created by qqq34 on 2016/1/15.
*/
public class UserActivity extends BaseActivity implements IUserActivityView {
@Bind(R.id.activity_user_spinner) //做一半发现一个新的绑定控件的方法,这个更简单 就用这个 了
BetterSpinner spinner2;
@Bind(R.id.til_name)
TextInputLayout TilName;
@Bind(R.id.activity_user_image)
SimpleDraweeView userImage;
@Bind(R.id.activity_user_button)
ButtonFlat imageButton;
@Bind(R.id.activity_user_updata_button)
ButtonRectangle updataButton;
@Bind(R.id.user_progressbar)
ProgressBar progressView;
private Context context;
private Toolbar toolbar;
private User user;
private UserActivityPresenter userActivityPresenter;
private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
private static final int PHOTO_REQUEST_CUT = 3;// 结果
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentLayout(R.layout.activity_user);
ButterKnife.bind(this);
context = this;
initdata();
initview();
initClick();
}
private void initdata() {
user = BmobUser.getCurrentUser(this, User.class);
userActivityPresenter = new UserActivityPresenter(UserActivity.this);
}
private void initview() {
setStarusBarBackground(R.mipmap.status);
setNavigationBarBackground(R.mipmap.navigation);
toolbar = getToolbar();
toolbar.setTitle("修改资料");
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.mipmap.ic_arrow_back_white_24dp);
String[] list = getResources().getStringArray(R.array.job);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, list);
spinner2.setAdapter(adapter);
spinner2.setText(list[(Integer.parseInt(user.getJob()) - 1)]);
TilName.getEditText().setText(user.getName());
if (user.getUser_image_url()!=null&&!user.getUser_image_url().isEmpty()){
Uri uri = Uri.parse(user.getUser_image_url());
userActivityPresenter.setImageUri(uri);
}
hideLoading();
}
private void initClick() {
toolbar.setNavigationOnClickListener(v -> finish());
imageButton.setOnClickListener(v -> {
Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
getAlbum.setType("image/*");
startActivityForResult(getAlbum, PHOTO_REQUEST_GALLERY);
});
TilName.getEditText().addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length()==0){
TilName.setError("名字不能为空");
updataButton.setEnabled(false);
}else {
updataButton.setEnabled(true);
TilName.setErrorEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
updataButton.setOnClickListener(v -> userActivityPresenter.updata(context,TilName.getEditText().getText().toString(),spinner2.getText().toString()));
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PHOTO_REQUEST_GALLERY:// 当选择从本地获取图片时
// 做非空判断,当我们觉得不满意想重新剪裁的时候便不会报异常,下同
if (data != null) {
userActivityPresenter.startPhotoZoom(data.getData());
} else {
}
break;
case PHOTO_REQUEST_CUT:// 返回的结果
if (data != null)
userActivityPresenter.setImageUri();
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void startCutActivity(Intent intent) {
startActivityForResult(intent, PHOTO_REQUEST_CUT);
}
@Override
public void setImageUri(Uri uri) {
userImage.setImageURI(uri);
}
@Override
public void showLoading() {
progressView.setVisibility(View.VISIBLE);
Log.d("UserActivity","progressbar显示!");
}
@Override
public void hideLoading() {
progressView.setVisibility(View.GONE);
}
@Override
public void setViewEnable(boolean isHide) {
spinner2.setEnabled(isHide);
TilName.getEditText().setEnabled(isHide);
userImage.setEnabled(isHide);
imageButton.setEnabled(isHide);
updataButton.setEnabled(isHide);
}
@Override
public void toMainActivity(User user) {
finish();
}
@Override
public void showFailedError(String s) {
Snackbar.make(toolbar, s, Snackbar.LENGTH_SHORT).setAction("重试", v -> userActivityPresenter.updata(context,TilName.getEditText().getText().toString(),spinner2.getText().toString())).show();
}
}
|
package cn.uway.cache;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.apache.mina.util.ConcurrentHashSet;
import cn.uway.config.LogMgr;
import cn.uway.util.FileUtil;
import cn.uway.util.StringUtil;
import cn.uway.util.TimeUtil;
public class MemoryCache extends AbstractCache {
private static final Logger LOGGER = LogMgr.getInstance().getSystemLogger();
public static Set<String> hasDoneFileSet = new ConcurrentHashSet<String>();
public FileCache fileCache;
public MemoryCache() {
}
// 内存/本地同步缓存
public void add(String file) {
hasDoneFileSet.add(file);
fileCache.add(file);
}
// 移除过期的文件
public static void removeOutDate(int retentionTime) {
try {
Date now = new Date();
for (String str : hasDoneFileSet) {
String name = str.substring(FileUtil.getLastSeparatorIndex(str) + 1);
String patternTime = StringUtil.getPattern(name, "\\d{8}");
Date time = TimeUtil.getyyyyMMddDate(patternTime);
if ((now.getTime() - time.getTime()) / 1000 / 60 / 60 / 24 >= retentionTime)
hasDoneFileSet.remove(str);
}
} catch (ParseException e) {
LOGGER.debug("清除内存报错");
}
}
public void addByBatch(List<String> fileList) {
if (fileList == null || fileList.size() == 0)
return;
for (String str : fileList) {
add(str);
}
}
public void load() throws Exception {
File file = fileCache.fileWriter.file;
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
hasDoneFileSet.add(line);
}
}
public static boolean isHave(String file) {
if (hasDoneFileSet.contains(file))
return true;
return false;
}
public FileCache getFileCache() {
return fileCache;
}
public void setFileCache(FileCache fileCache) {
this.fileCache = fileCache;
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
final Set<String> hasDoneFileSet = new ConcurrentHashSet<String>();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
int count = 100000;
while (count-- > 0) {
hasDoneFileSet.add("123" + count);
}
System.out.println("add over");
}
});
thread1.start();
Thread.sleep(1000);
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
int count = 0;
for (String str : hasDoneFileSet) {
hasDoneFileSet.contains(str);
count++;
}
System.out.println("remove over:" + count);
}
});
thread2.start();
}
}
|
package ca.mohawk.jdw.shifty.clientapi.net;
/*
I, Josh Maione, 000320309 certify that this material is my original work.
No other person's work has been used without due acknowledgement.
I have not made my work available to anyone else.
Module: client-api
Developed By: Josh Maione (000320309)
*/
public class Packet extends Buffer {
private final Opcode opcode;
public Packet(final Opcode opcode){
this.opcode = opcode;
}
public Packet(final Opcode opcode,
final Buffer payload){
this(opcode);
writeBuffer(payload);
}
public Opcode opcode(){
return opcode;
}
@Override
public Packet writeBuffer(final Buffer b){
super.writeBuffer(b);
return this;
}
@Override
public Packet writeByte(final int b){
super.writeByte(b);
return this;
}
@Override
public Packet writeChar(final char c){
super.writeChar(c);
return this;
}
@Override
public Packet writeShort(final int s){
super.writeShort(s);
return this;
}
@Override
public Packet writeInt(final int i){
super.writeInt(i);
return this;
}
@Override
public Packet writeLong(final long l){
super.writeLong(l);
return this;
}
@Override
public Packet writeString(final String s){
super.writeString(s);
return this;
}
@Override
public Packet writeBytes(final byte[] bytes){
super.writeBytes(bytes);
return this;
}
}
|
/**
* @author I077988
*/
package com.cnk.travelogix.suppliers.service.impl;
import de.hybris.platform.servicelayer.search.FlexibleSearchService;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.cnk.travelogix.supplier.mappings.model.AbstractSupplierMappingModel;
import com.cnk.travelogix.supplier.mappings.product.model.SupplierProductModel;
import com.cnk.travelogix.suppliers.service.SupplierProductMappingService;
import com.cnk.travelogix.suppliers.util.CsvWriter;
import com.cnk.travelogix.suppliers.util.SupplierUtils;
/**
* @author I077988
*/
public class SupplierProductMappingServiceImpl implements SupplierProductMappingService {
private static final Logger LOG = Logger.getLogger(SupplierProductMappingServiceImpl.class);
@Autowired
private SupplierUtils supplierUtils;
@Autowired
private FlexibleSearchService flexibleSearchService;
private static final String FILE_HEADER = "SupplierID,SupplierName,SupplierType,ProductType,Active";
@Override
public boolean getAllSupplierProducts() {
try {
final CsvWriter csvWriter = this.getCsvWriter();
final SupplierProductModel supplierProductModelReq = new SupplierProductModel();
supplierProductModelReq.setActive(Boolean.TRUE);
final List<SupplierProductModel> supplierProductModelList = flexibleSearchService.getModelsByExample(supplierProductModelReq);
for (SupplierProductModel supplierProductModel : supplierProductModelList) {
this.writeSupplierProductRecord(csvWriter, supplierProductModel);
}
csvWriter.close();
return true;
} catch (final Exception e) {
LOG.info("#getAllSupplierProducts" + e.getMessage(), e);
return false;
}
}
@Override
public boolean mapUpdatedSupplierProduct(final SupplierProductModel supplierProductModelReq) {
try {
final CsvWriter csvWriter = this.getCsvWriter();
final SupplierProductModel supplierProductModel = flexibleSearchService.getModelByExample(supplierProductModelReq);
this.writeSupplierProductRecord(csvWriter, supplierProductModel);
csvWriter.close();
return true;
} catch (final Exception e) {
LOG.info("#mapUpdatedSupplierProduct" + e.getMessage(), e);
return false;
}
}
/**
* @return csvWriter
* @throws IOException
*/
private CsvWriter getCsvWriter() throws IOException {
final String mappingOutputFile = supplierUtils.getMappingOutputFile("product.mapping.path.key", "supplier_product_map_");
final boolean alreadyExists = new File(mappingOutputFile).exists();
final CsvWriter csvWriter = new CsvWriter(new FileWriter(mappingOutputFile, true), SupplierUtils.COMMA_DELIMITER);
if (!alreadyExists) {
csvWriter.write(FILE_HEADER);
csvWriter.endRecord();
}
return csvWriter;
}
/**
* @param csvWriter
* @param supplierProductModel
* @throws IOException
*/
private void writeSupplierProductRecord(final CsvWriter csvWriter, SupplierProductModel supplierProductModel) throws IOException {
/*final Collection<AbstractSupplierMappingModel> mappings = supplierProductModel.getMappings();
for (AbstractSupplierMappingModel abstractSupplierMappingModel : mappings) {
csvWriter.write(abstractSupplierMappingModel.getSupplier().getCode());
csvWriter.write(abstractSupplierMappingModel.getSupplier().getName());
csvWriter.write(abstractSupplierMappingModel.getSupplier().getSupplierType().getType());
csvWriter.write(supplierProductModel.getCode());
csvWriter.write(supplierProductModel.getActive().toString());
csvWriter.endRecord();
}*/
}
}
|
package iterator;
import java.util.List;
interface Library {
Iterator getIterator();
List<Book> getBooks();
}
class LibraryImpl implements Library {
private List<Book> books;
LibraryImpl(List<Book> books) {
this.books = books;
}
public Iterator getIterator() {
return new BookIterator();
}
public List<Book> getBooks() {
return books;
}
private class BookIterator implements Iterator {
int index = 0;
public boolean hasNext() {
return index < books.size();
}
public Object next() {
return books.get(index++);
}
}
}
class Book {
}
interface Iterator {
Object next();
boolean hasNext();
}
|
package com.mygdx.ObjectInfo;
public class MonsterStatsInfo extends AbstractStatsInfo{
}
|
package com.danboard.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
/**
* Helper method related to IO operations
*/
public class IOHelpers {
/**
* @param is
* @return a string
* @throws IOException
*/
static public String convertStreamToString(InputStream is)
throws IOException {
final char[] buffer = new char[0x10000];
StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(is, "UTF-8");
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read > 0) {
out.append(buffer, 0, read);
}
} while (read >= 0);
return out.toString();
}
}
|
package com.simha.SpringJPADemoForQueryResults;
import java.util.List;
import java.util.function.Consumer;
import java.util.Arrays;
public class ConsumerDemo {
public static void main(String[] args) {
Consumer<Integer> consumer = (t) -> System.out.println("printing.... " + t);
consumer.accept(40);
List<Integer> listIntegers = Arrays.asList(1, 2, 3, 4);
listIntegers.stream().forEach(consumer);
System.out.println("hi hello mr tingers Mr Simhachalam Amara ");
}
}
|
package retro;
public class ApiUtil {
private static final String BASE_URL = "https://ask.osify.com/wp-json/wp/";
private static final String WOO_URL = "https://lom-or.com/wp-json/wc/";
public static PostServiceInterface getPostService(){
return RetrofitAPI.getRetrofit(BASE_URL).create(PostServiceInterface.class);
}
public static WooServiceInterface getWooService() {
return RetrofitAPI.getRetrofit(WOO_URL).create(WooServiceInterface.class);
}
}
|
package com.dennistjahyadigotama.soaya.activities.warta_ubaya_activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import com.dennistjahyadigotama.soaya.R;
import com.dennistjahyadigotama.soaya.activities.warta_ubaya_activity.adapter.FullScreenImageAdapter;
import java.util.ArrayList;
/**
* Created by Denn on 9/20/2016.
*/
public class WartaUbayaActivity extends AppCompatActivity {
ViewPager viewPager;
TextView tvPage;
ArrayList<String> imagePath = new ArrayList<>();
Toolbar toolbar;
int totalpage;
String edisi,location;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.warta_ubaya_activity);
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
totalpage = getIntent().getIntExtra("totalpage",0);
edisi = getIntent().getStringExtra("edisi");
location = getIntent().getStringExtra("location");
getSupportActionBar().setTitle("Edisi "+edisi);
tvPage = (TextView)findViewById(R.id.tvPage);
tvPage.setText("Page 1");
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
tvPage.setText("Page "+(position+1));
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
for(int i=1;i<=totalpage;i++)
{
imagePath.add(location+i+".jpg");
}
FullScreenImageAdapter adapter = new FullScreenImageAdapter(this,imagePath);
viewPager.setAdapter(adapter);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.buiminhduc.repository;
import com.buiminhduc.common.annotation.Repository;
import com.buiminhduc.model.entity.ProductEntity;
import com.buiminhduc.paging.Pageable;
import java.util.List;
public interface ProductRepository extends JpaRepository<ProductEntity, Integer> {
List<ProductEntity> findAll();
ProductEntity findById(Integer id);
List<ProductEntity> findAllLimit3();
void deleteByIds(int[] ids);
}
|
package com.shagaba.kickstarter.rest.domain.profile;
public class Address {
protected String name;
protected String firstName;
protected String lastName;
protected String companyName;
protected String addressLine1;
protected String addressLine2;
protected String addressLine3;
protected String city;
protected String state;
protected String county;
protected String country;
protected String postalCode;
protected String zip;
protected Phone phonePrimary;
protected Phone phoneSecondary;
protected Phone phoneFax;
protected String longitude;
protected String latitude;
protected Boolean isDefault;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the companyName
*/
public String getCompanyName() {
return companyName;
}
/**
* @param companyName the companyName to set
*/
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
/**
* @return the addressLine1
*/
public String getAddressLine1() {
return addressLine1;
}
/**
* @param addressLine1 the addressLine1 to set
*/
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
/**
* @return the addressLine2
*/
public String getAddressLine2() {
return addressLine2;
}
/**
* @param addressLine2 the addressLine2 to set
*/
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
/**
* @return the addressLine3
*/
public String getAddressLine3() {
return addressLine3;
}
/**
* @param addressLine3 the addressLine3 to set
*/
public void setAddressLine3(String addressLine3) {
this.addressLine3 = addressLine3;
}
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* @return the state
*/
public String getState() {
return state;
}
/**
* @param state the state to set
*/
public void setState(String state) {
this.state = state;
}
/**
* @return the county
*/
public String getCounty() {
return county;
}
/**
* @param county the county to set
*/
public void setCounty(String county) {
this.county = county;
}
/**
* @return the country
*/
public String getCountry() {
return country;
}
/**
* @param country the country to set
*/
public void setCountry(String country) {
this.country = country;
}
/**
* @return the postalCode
*/
public String getPostalCode() {
return postalCode;
}
/**
* @param postalCode the postalCode to set
*/
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
/**
* @return the zip
*/
public String getZip() {
return zip;
}
/**
* @param zip the zip to set
*/
public void setZip(String zip) {
this.zip = zip;
}
/**
* @return the phonePrimary
*/
public Phone getPhonePrimary() {
return phonePrimary;
}
/**
* @param phonePrimary the phonePrimary to set
*/
public void setPhonePrimary(Phone phonePrimary) {
this.phonePrimary = phonePrimary;
}
/**
* @return the phoneSecondary
*/
public Phone getPhoneSecondary() {
return phoneSecondary;
}
/**
* @param phoneSecondary the phoneSecondary to set
*/
public void setPhoneSecondary(Phone phoneSecondary) {
this.phoneSecondary = phoneSecondary;
}
/**
* @return the phoneFax
*/
public Phone getPhoneFax() {
return phoneFax;
}
/**
* @param phoneFax the phoneFax to set
*/
public void setPhoneFax(Phone phoneFax) {
this.phoneFax = phoneFax;
}
/**
* @return the longitude
*/
public String getLongitude() {
return longitude;
}
/**
* @param longitude the longitude to set
*/
public void setLongitude(String longitude) {
this.longitude = longitude;
}
/**
* @return the latitude
*/
public String getLatitude() {
return latitude;
}
/**
* @param latitude the latitude to set
*/
public void setLatitude(String latitude) {
this.latitude = latitude;
}
/**
* @return the isDefault
*/
public Boolean getIsDefault() {
return isDefault;
}
/**
* @param isDefault the isDefault to set
*/
public void setIsDefault(Boolean isDefault) {
this.isDefault = isDefault;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String
.format("Address {name=%s, firstName=%s, lastName=%s, companyName=%s, addressLine1=%s, addressLine2=%s, addressLine3=%s, city=%s, state=%s, county=%s, country=%s, postalCode=%s, zip=%s, phonePrimary=%s, phoneSecondary=%s, phoneFax=%s, longitude=%s, latitude=%s, isDefault=%s}",
name, firstName, lastName, companyName, addressLine1, addressLine2, addressLine3, city, state, county, country,
postalCode, zip, phonePrimary, phoneSecondary, phoneFax, longitude, latitude, isDefault);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((addressLine1 == null) ? 0 : addressLine1.hashCode());
result = prime * result + ((addressLine2 == null) ? 0 : addressLine2.hashCode());
result = prime * result + ((addressLine3 == null) ? 0 : addressLine3.hashCode());
result = prime * result + ((city == null) ? 0 : city.hashCode());
result = prime * result + ((companyName == null) ? 0 : companyName.hashCode());
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((county == null) ? 0 : county.hashCode());
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((isDefault == null) ? 0 : isDefault.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result + ((latitude == null) ? 0 : latitude.hashCode());
result = prime * result + ((longitude == null) ? 0 : longitude.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((phoneFax == null) ? 0 : phoneFax.hashCode());
result = prime * result + ((phonePrimary == null) ? 0 : phonePrimary.hashCode());
result = prime * result + ((phoneSecondary == null) ? 0 : phoneSecondary.hashCode());
result = prime * result + ((postalCode == null) ? 0 : postalCode.hashCode());
result = prime * result + ((state == null) ? 0 : state.hashCode());
result = prime * result + ((zip == null) ? 0 : zip.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Address other = (Address) obj;
if (addressLine1 == null) {
if (other.addressLine1 != null)
return false;
} else if (!addressLine1.equals(other.addressLine1))
return false;
if (addressLine2 == null) {
if (other.addressLine2 != null)
return false;
} else if (!addressLine2.equals(other.addressLine2))
return false;
if (addressLine3 == null) {
if (other.addressLine3 != null)
return false;
} else if (!addressLine3.equals(other.addressLine3))
return false;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (companyName == null) {
if (other.companyName != null)
return false;
} else if (!companyName.equals(other.companyName))
return false;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (county == null) {
if (other.county != null)
return false;
} else if (!county.equals(other.county))
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (isDefault == null) {
if (other.isDefault != null)
return false;
} else if (!isDefault.equals(other.isDefault))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (latitude == null) {
if (other.latitude != null)
return false;
} else if (!latitude.equals(other.latitude))
return false;
if (longitude == null) {
if (other.longitude != null)
return false;
} else if (!longitude.equals(other.longitude))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (phoneFax == null) {
if (other.phoneFax != null)
return false;
} else if (!phoneFax.equals(other.phoneFax))
return false;
if (phonePrimary == null) {
if (other.phonePrimary != null)
return false;
} else if (!phonePrimary.equals(other.phonePrimary))
return false;
if (phoneSecondary == null) {
if (other.phoneSecondary != null)
return false;
} else if (!phoneSecondary.equals(other.phoneSecondary))
return false;
if (postalCode == null) {
if (other.postalCode != null)
return false;
} else if (!postalCode.equals(other.postalCode))
return false;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (zip == null) {
if (other.zip != null)
return false;
} else if (!zip.equals(other.zip))
return false;
return true;
}
}
|
package com.cnk.travelogix.operations.facades.populator;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import com.cnk.travelogix.common.core.model.receipts.ReceiptDetailsModel;
import com.cnk.travelogix.operations.data.TravelogixReceiptDetailsData;
/**
* The travelogix receipt details populator
*/
public class TravelogixReceiptDetailsPopulator implements Populator<ReceiptDetailsModel, TravelogixReceiptDetailsData>
{
@Override
public void populate(final ReceiptDetailsModel source, final TravelogixReceiptDetailsData target) throws ConversionException
{
target.setAppliedCost(source.getAppliedCost());
target.setInvoiceID(source.getInvoiceID());
target.setReceiptId(source.getReceiptId());
}
}
|
package com.ss.android.ugc.aweme.miniapp.g;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import com.ss.android.ugc.aweme.miniapp.MiniAppService;
import com.ss.android.ugc.aweme.miniapp.a;
import com.ss.android.ugc.aweme.miniapp.c;
import com.ss.android.ugc.aweme.miniapp.f;
import com.ss.android.ugc.aweme.miniapp.g;
import com.ss.android.ugc.aweme.miniapp_api.a.l;
import com.tt.miniapphost.process.HostProcessBridge;
import com.tt.option.u.a;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;
public class w extends a {
private List<g> a = new ArrayList<g>();
public w() {
this.a.add(new a());
this.a.add(new c());
}
public boolean handleAppbrandDisablePage(Context paramContext, String paramString) {
for (g g : this.a) {
if (g.a(paramString))
return g.a(paramContext, paramString);
}
return false;
}
public void jumpToWebView(Context paramContext, String paramString1, String paramString2, boolean paramBoolean) {
Integer integer;
StringBuilder stringBuilder = new StringBuilder("sslocal://webview?url=");
stringBuilder.append(Uri.encode(paramString1));
stringBuilder.append("&title=");
stringBuilder.append(Uri.encode(paramString2));
stringBuilder.append("&hide_bar=");
if (paramBoolean) {
paramString1 = "1";
} else {
integer = Integer.valueOf(0);
}
stringBuilder.append(integer);
String str = stringBuilder.toString();
if (paramContext != null) {
l l = MiniAppService.inst().getRouterDepend();
if (l != null)
l.a(paramContext, str);
}
}
public boolean navigateToVideoView(Activity paramActivity, String paramString) {
Intent intent = new Intent();
intent.putExtra("id", paramString);
MiniAppService.inst().getRouterDepend().a(paramActivity, intent);
return true;
}
public boolean openCustomerService(Context paramContext, String paramString) {
if (paramContext != null) {
jumpToWebView(paramContext, paramString, "", false);
return true;
}
return false;
}
public boolean openProfile(Activity paramActivity, String paramString) {
HostProcessBridge.logEvent("enter_personal_detail", new JSONObject((f.a().a("to_user_id", paramString).a("enter_from", "mp_ranklist")).a));
l l = MiniAppService.inst().getRouterDepend();
return (l != null) ? l.a((Context)paramActivity, paramString, "", "mp_ranklist", "follow_button") : false;
}
public boolean openSchema(Context paramContext, String paramString) {
// Byte code:
// 0: aload_1
// 1: instanceof android/app/Activity
// 4: ifeq -> 30
// 7: aload_1
// 8: checkcast android/app/Activity
// 11: invokevirtual getIntent : ()Landroid/content/Intent;
// 14: astore_3
// 15: aload_3
// 16: ifnull -> 30
// 19: aload_3
// 20: ldc 'class_name'
// 22: invokevirtual getStringExtra : (Ljava/lang/String;)Ljava/lang/String;
// 25: astore #4
// 27: goto -> 33
// 30: aconst_null
// 31: astore #4
// 33: aload_2
// 34: astore_3
// 35: aload_2
// 36: ifnull -> 57
// 39: aload_2
// 40: invokestatic parse : (Ljava/lang/String;)Landroid/net/Uri;
// 43: invokevirtual buildUpon : ()Landroid/net/Uri$Builder;
// 46: ldc 'from'
// 48: aload #4
// 50: invokevirtual appendQueryParameter : (Ljava/lang/String;Ljava/lang/String;)Landroid/net/Uri$Builder;
// 53: invokevirtual toString : ()Ljava/lang/String;
// 56: astore_3
// 57: invokestatic inst : ()Lcom/ss/android/ugc/aweme/miniapp/MiniAppService;
// 60: invokevirtual getRouterDepend : ()Lcom/ss/android/ugc/aweme/miniapp_api/a/l;
// 63: astore_2
// 64: aload_2
// 65: ifnull -> 78
// 68: aload_2
// 69: aload_1
// 70: aload_3
// 71: iconst_0
// 72: invokeinterface a : (Landroid/content/Context;Ljava/lang/String;Z)Z
// 77: ireturn
// 78: iconst_0
// 79: ireturn
}
public boolean supportCustomerService() {
return true;
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\ss\androi\\ugc\aweme\miniapp\g\w.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package Practice;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class ReflectDemo
{
}
class Apple
{
private int age;
public String name;
public void setName(String name)
{
this.name = name;
}
private Apple()
{
System.out.println("123");
}
public Apple(int age, String name)
{
this.name = name;
this.age = age;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public static void main(String[] args)
{
try
{
Class cls = Class.forName("Practice.Apple");
Constructor constructor = cls.getConstructor(int.class, String.class);
Apple apple = (Apple) constructor.newInstance(13, "¶¾Æ»¹û");
Method method = cls.getMethod("setAge", int.class);
method.invoke(apple,10);
method.setAccessible(true);
System.out.println(apple.getAge());
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e)
{
e.printStackTrace();
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package IServiceSupport;
import com.douwe.generic.dao.DataAccessException;
import java.util.List;
import lappa.smsbanking.Entities.Adresse;
import lappa.smsbanking.Entities.Personne;
/**
*
* @author lappa
*/
public interface IServiceAdresse {
public Adresse findByIdA(Long id) throws DataAccessException;
public Adresse findByTypeAdresse(String typeAdresse) throws DataAccessException;
public Personne findByIdClient(String idClient) throws DataAccessException;
public void save(Adresse c, Long idu) throws DataAccessException;
public void delete(Long id) throws DataAccessException;
public void update(Adresse c) throws DataAccessException;
public List<Adresse> findAll() throws DataAccessException;
public Adresse findById(Long id) throws DataAccessException;
}
|
package com.computerstudent.madpractical.Practical_25;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.computerstudent.madpractical.R;
public class loginForm3 extends AppCompatActivity {
EditText txtUsername,txtPassword;
Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_form3);
txtUsername=findViewById(R.id.txtUsername);
txtPassword=findViewById(R.id.txtPassword);
btnLogin=findViewById(R.id.btnLogin);
btnLogin.setEnabled(false);
txtUsername.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (checkEmptyInput())
{
btnLogin.setEnabled(true);
}
else {
btnLogin.setEnabled(false);
}
}
});
txtPassword.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (checkEmptyInput())
{
btnLogin.setEnabled(true);
}
else {
btnLogin.setEnabled(false);
}
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkEmptyInput())
{
if(txtUsername.getText().toString().equals("sanket")&&txtPassword.getText().toString().equals("1234"))
{
Toast.makeText(getApplicationContext(), "login Successful....", Toast.LENGTH_SHORT).show();
clearInput();
}
else {
Toast.makeText(getApplicationContext(), "login Unsuccessful....", Toast.LENGTH_SHORT).show();
clearInput();
}
}
}
});
}
boolean checkEmptyInput() {
boolean flag = true;
EditText[] inputGroup = new EditText[]{txtUsername, txtPassword};
for (int i = 0; i < 2; i++) {
if (TextUtils.isEmpty(inputGroup[i].getText().toString())) {
flag = false;
}
}
return flag;
}
void clearInput()
{
txtPassword.setText("");
txtUsername.setText("");
}
} |
package com.example.recyclerview.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.example.recyclerview.adapter.CourseTopicAdapter;
import com.example.recyclerview.data.Course;
import com.example.recyclerview.data.CourseDAO;
import com.example.recyclerview.data.Topic;
import com.example.recyclerview.data.TopicDAO;
import com.example.recyclerview.R;
import com.example.recyclerview.data.WordDAO;
import java.util.ArrayList;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class TopicActivity extends AppCompatActivity implements CourseTopicAdapter.OnItemClickListener {
public static final String TOPIC_NAME = "TOPIC_NAME";
public static final String FAMILY = "Family";
public static final String ANIMAL = "Animal";
public static final String CLOTHES = "Clothes";
public static final String COLOR = "Color";
public static final String FRUIT = "Fruit";
public static final String COOKING = "Cooking";
public static final String MUSIC = "Music";
public static final String NUMBER = "Number";
public static final String SCHOOL = "School";
public static final String SPORT = "Sport";
public static final String TRAFFIC = "Traffic";
public static final String VEGETABLES = "Vegetables";
public static final String WEATHER = "Weather";
public static final String HOSPITAL = "Hospital";
public static final String RESTAURANT = "Restaurant";
public static final String ADJECTIVE = "Adjective";
public static final String ACTION = "Action";
private static final int SETTING_ACTIVITY_REQUEST = 1000;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_basic_english);
Intent parentIntent = getIntent();
String courseTitle = parentIntent.getStringExtra(MainActivity.COURSE_DATA);
ArrayList<Topic> topics = setupTopics(courseTitle);
setupRecyclerView(topics);
setTitle(courseTitle);
}
private void setupRecyclerView(ArrayList<Topic> topics) {
RecyclerView recyclerView = findViewById(R.id.basicEnglishRecyclerView);
CourseTopicAdapter courseTopicAdapter =
new CourseTopicAdapter(TopicActivity.this, topics, this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(courseTopicAdapter);
}
private ArrayList<Topic> setupTopics(String courseTitle) {
Course course = CourseDAO.fromContext(this).getCourseByTitle(courseTitle);
TopicDAO topicDAO = TopicDAO.fromContext(this);
ArrayList<Topic> topics = topicDAO.getTopicsByCourseId(course.getId());
WordDAO wordDAO = WordDAO.fromContext(this);
for (Topic topic : topics) {
topic.setNumberOfWords(wordDAO.getNumberOfWordsByCategory(topic.getName()));
}
return topics;
}
@Override
public void onItemClick(Topic topic) {
Intent intent = new Intent(TopicActivity.this, WordListActivity.class);
intent.putExtra(TOPIC_NAME, topic.getName());
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_setting) {
Intent intent = new Intent(TopicActivity.this, SettingActivity.class);
startActivityForResult(intent, TopicActivity.SETTING_ACTIVITY_REQUEST);
}
return super.onOptionsItemSelected(item);
}
} |
package com.greenapex.quizapp.controllertest;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.greenapex.quizapp.controller.AnswerController;
import com.greenapex.quizapp.entity.AnswerModule;
import com.greenapex.quizapp.service.AnswerService;
@AutoConfigureMockMvc
@ContextConfiguration
@SpringBootTest(classes= {AnswerControllerTest.class})
public class AnswerControllerTest {
@Autowired
private MockMvc mockMvc;
@Mock
private AnswerService answerService;
@InjectMocks
private AnswerController answerController;
@BeforeEach
public void setUp() {
mockMvc=MockMvcBuilders.standaloneSetup(answerController).build();
}
@Test
@Order(1)
public void insertAnswerTest() throws Exception {
AnswerModule answer = new AnswerModule();
answer.setAnswer_id(1);
answer.setAnswer("JDK");
answer.setIs_correct(true);
answer.setQuestion_id(1);
when(answerService.addAnswer(answer)).thenReturn(answer);
ObjectMapper mapper=new ObjectMapper();
String jsonbody=mapper.writeValueAsString(answer);
this.mockMvc.perform(post("/addanswer")
.accept(MediaType.APPLICATION_JSON)
.content(jsonbody)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andDo(print());
System.out.println("Answer added Successfully");
}
@Test
@Order(2)
public void updateAnswerTest() throws Exception {
AnswerModule answer = new AnswerModule();
answer.setAnswer_id(1);
answer.setAnswer("JRE");
answer.setIs_correct(true);
answer.setQuestion_id(1);
when(answerService.updateAnswer(answer)).thenReturn(answer);
ObjectMapper mapper=new ObjectMapper();
String jsonbody=mapper.writeValueAsString(answer);
this.mockMvc.perform(put("/updateanswer")
.accept(MediaType.APPLICATION_JSON)
.content(jsonbody)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andDo(print());
System.out.println("Answer Updted Successfully");
}
@Test
@Order(3)
public void getAnswerByIdTest() throws Exception {
AnswerModule answer = new AnswerModule();
answer.setAnswer_id(1);
answer.setAnswer("Dynamic");
answer.setIs_correct(true);
answer.setQuestion_id(1);
when(answerService.getAnswerById(1)).thenReturn(answer);
this.mockMvc.perform(get("/getanswerbyansid/{answer_id}",1))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath(".answer_id").value(1))
.andExpect(MockMvcResultMatchers.jsonPath(".answer").value("Dynamic"))
.andExpect(MockMvcResultMatchers.jsonPath(".is_correct").value(true))
.andExpect(MockMvcResultMatchers.jsonPath(".question_id").value(1))
.andDo(print());
}
@Test
@Order(4)
public void getQuestionByQuizIdTest() throws Exception {
AnswerModule answer = new AnswerModule();
answer.setAnswer_id(1);
answer.setAnswer("C");
answer.setQuestion_id(1);
answer.setIs_correct(false);
AnswerModule answer1 = new AnswerModule();
answer1.setAnswer_id(2);
answer1.setAnswer("C++");
answer1.setQuestion_id(1);
answer1.setIs_correct(true);
AnswerModule answer2 = new AnswerModule();
answer2.setAnswer_id(3);
answer2.setAnswer("Python");
answer2.setQuestion_id(1);
answer2.setIs_correct(false);
AnswerModule answer3 = new AnswerModule();
answer3.setAnswer_id(4);
answer3.setAnswer("Perl");
answer3.setQuestion_id(1);
answer3.setIs_correct(false);
List<AnswerModule> answers = new ArrayList<>();
answers.add(answer);
answers.add(answer1);
answers.add(answer2);
answers.add(answer3);
when(answerService.getAnswer(1)).thenReturn(answers);
this.mockMvc.perform(get("/getanswerbyqnid/{question_id}",1))
.andExpect(status().isOk())
.andDo(print());
}
}
|
package edu.pdx.advocate.model;
import java.sql.SQLData;
import java.sql.SQLException;
import java.sql.SQLInput;
import java.sql.SQLOutput;
import javax.xml.bind.annotation.XmlTransient;
public class Course implements SQLData {
private String crn;
private String course;
private String title;
private String beginTime;
private String endTime;
private String location;
private String days;
private String startdate;
private String enddate;
private String sqlType;
public String getSQLTypeName() throws SQLException {
return this.sqlType;
}
public void readSQL(SQLInput stream, String typeName) throws SQLException {
this.sqlType = typeName;
this.crn = stream.readString();
this.course = stream.readString();
this.title = stream.readString();
this.beginTime = stream.readString();
this.endTime = stream.readString();
this.location = stream.readString();
this.days = stream.readString();
this.startdate = stream.readString();
this.enddate = stream.readString();
}
public void writeSQL(SQLOutput stream) throws SQLException {
stream.writeString(this.crn);
stream.writeString(this.course);
stream.writeString(this.title);
stream.writeString(this.beginTime);
stream.writeString(this.endTime);
stream.writeString(this.location);
stream.writeString(this.days);
stream.writeString(this.startdate);
stream.writeString(this.enddate);
}
public String getCrn() {
return crn;
}
public void setCrn(String crn) {
this.crn = crn;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBeginTime() {
return beginTime;
}
public void setBeginTime(String beginTime) {
this.beginTime = beginTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDays() {
return days;
}
public void setDays(String days) {
this.days = days;
}
public String getStartdate() {
return startdate;
}
public void setStartdate(String startdate) {
this.startdate = startdate;
}
public String getEnddate() {
return enddate;
}
public void setEnddate(String enddate) {
this.enddate = enddate;
}
@XmlTransient
public String getSqlType() {
return sqlType;
}
public void setSqlType(String sqlType) {
this.sqlType = sqlType;
}
}
|
// O(n) time, O(1) space
class Solution {
public int singleNonDuplicate(int[] nums) {
//use XOR to get the single element
int res = nums[0];
for (int i = 1; i < nums.length; i++) {
res ^= nums[i];
}
return res;
}
} |
package com.cskaoyan.service;
import com.cskaoyan.bean.MaterialMessage;
import java.util.List;
/**
* @author q4work
*/
public interface MaterialMessageService {
public List<MaterialMessage> queryAllMaterialMessage();
public boolean insertMaterialMessage(MaterialMessage materialMessage);
public List<MaterialMessage> queryMaterialById(String searchValue);
public List<MaterialMessage> queryMaterialByType(String searchValue);
public int deleteMaterialById(String[] ids);
int materialEdit(MaterialMessage materialMessage);
}
|
package smart.repository;
import smart.entity.BrandEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface BrandRepository extends JpaRepository<BrandEntity, Long> {
@Query(value = "select * from t_brand where id = ? for update", nativeQuery = true)
BrandEntity findByIdForUpdate(long id);
}
|
package com.websharp.dwtz.dao;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.DaoConfig;
import com.websharp.dwtz.dao.EntityLocation;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table ENTITY_LOCATION.
*/
public class EntityLocationDao extends AbstractDao<EntityLocation, Void> {
public static final String TABLENAME = "ENTITY_LOCATION";
/**
* Properties of entity EntityLocation.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property ID = new Property(0, Integer.class, "ID", false, "ID");
public final static Property Name = new Property(1, String.class, "Name", false, "NAME");
public final static Property TraName = new Property(2, String.class, "TraName", false, "TRA_NAME");
public final static Property EName = new Property(3, String.class, "EName", false, "ENAME");
public final static Property ParentID = new Property(4, Integer.class, "ParentID", false, "PARENT_ID");
public final static Property LocationLevel = new Property(5, Integer.class, "LocationLevel", false, "LOCATION_LEVEL");
};
public EntityLocationDao(DaoConfig config) {
super(config);
}
public EntityLocationDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "'ENTITY_LOCATION' (" + //
"'ID' INTEGER," + // 0: ID
"'NAME' TEXT," + // 1: Name
"'TRA_NAME' TEXT," + // 2: TraName
"'ENAME' TEXT," + // 3: EName
"'PARENT_ID' INTEGER," + // 4: ParentID
"'LOCATION_LEVEL' INTEGER);"); // 5: LocationLevel
}
/** Drops the underlying database table. */
public static void dropTable(SQLiteDatabase db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'ENTITY_LOCATION'";
db.execSQL(sql);
}
/** @inheritdoc */
@Override
protected void bindValues(SQLiteStatement stmt, EntityLocation entity) {
stmt.clearBindings();
Integer ID = entity.getID();
if (ID != null) {
stmt.bindLong(1, ID);
}
String Name = entity.getName();
if (Name != null) {
stmt.bindString(2, Name);
}
String TraName = entity.getTraName();
if (TraName != null) {
stmt.bindString(3, TraName);
}
String EName = entity.getEName();
if (EName != null) {
stmt.bindString(4, EName);
}
Integer ParentID = entity.getParentID();
if (ParentID != null) {
stmt.bindLong(5, ParentID);
}
Integer LocationLevel = entity.getLocationLevel();
if (LocationLevel != null) {
stmt.bindLong(6, LocationLevel);
}
}
/** @inheritdoc */
@Override
public Void readKey(Cursor cursor, int offset) {
return null;
}
/** @inheritdoc */
@Override
public EntityLocation readEntity(Cursor cursor, int offset) {
EntityLocation entity = new EntityLocation( //
cursor.isNull(offset + 0) ? null : cursor.getInt(offset + 0), // ID
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // Name
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // TraName
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // EName
cursor.isNull(offset + 4) ? null : cursor.getInt(offset + 4), // ParentID
cursor.isNull(offset + 5) ? null : cursor.getInt(offset + 5) // LocationLevel
);
return entity;
}
/** @inheritdoc */
@Override
public void readEntity(Cursor cursor, EntityLocation entity, int offset) {
entity.setID(cursor.isNull(offset + 0) ? null : cursor.getInt(offset + 0));
entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setTraName(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setEName(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
entity.setParentID(cursor.isNull(offset + 4) ? null : cursor.getInt(offset + 4));
entity.setLocationLevel(cursor.isNull(offset + 5) ? null : cursor.getInt(offset + 5));
}
/** @inheritdoc */
@Override
protected Void updateKeyAfterInsert(EntityLocation entity, long rowId) {
// Unsupported or missing PK type
return null;
}
/** @inheritdoc */
@Override
public Void getKey(EntityLocation entity) {
return null;
}
/** @inheritdoc */
@Override
protected boolean isEntityUpdateable() {
return true;
}
}
|
package BD;
import fabrica.Conexao;
import fabrica.GeralConst;
import helper.JSHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import util.Tabela;
public class TabelaDao {
public ArrayList<Object> getTodas() {
ArrayList<Object> todos = new ArrayList<Object>();
Connection con = null;
PreparedStatement pstm = null;
try{
con = Conexao.conectar();
pstm = con.prepareStatement("select * from information_schema.tables where table_schema='"+GeralConst.schemaConexao+"' ");
TabelaBean tabela = null;
CampoDao campoDao = new CampoDao();
DetailDao detailDao = new DetailDao();
ResultSet rs = pstm.executeQuery();
while(rs.next()){
tabela = new TabelaBean();
tabela.setNome(rs.getString("TABLE_NAME"));
tabela.setCaption(rs.getString("TABLE_COMMENT"));
tabela.setCampos(campoDao.getTodosCampos(tabela.getNome()));
tabela.setCamposPK(campoDao.getTodosCamposPK(tabela.getNome()));
tabela.setDetails(detailDao.getDetailsTabela(tabela.getNome()));
todos.add(tabela);
}
PreencherEhDetail(todos);
return todos;
}catch(Exception ex){
System.err.println(ex.getMessage());
return null;
}finally{
try {
if(pstm != null) pstm.close();
if(con != null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private TabelaBean getTabela(ArrayList<Object> arrayDeTabelas, String nome){
for(int i=0; i < arrayDeTabelas.size(); i++){
TabelaBean tabela = (TabelaBean) arrayDeTabelas.get(i);
if(tabela.getNome().equalsIgnoreCase(nome))
return tabela;
}
return null;
}
public void PreencherEhDetail(ArrayList<Object> todos){
ArrayList<Object> todosDetail = todos;
for(int i=0; i < todos.size(); i++){
TabelaBean tabela = (TabelaBean) todos.get(i);
for(int i1=0; i1 < tabela.getQtdDetails(); i1++){
TabelaBean tabelaDetail = getTabela(todosDetail, tabela.getDetail(i1).getNomeTabelaDetail());
tabelaDetail.setEhDetail(true);
}
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package UpTlax.Practica10;
import java.io.FileFiader;
import java.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author nueva
*/
public class Archivo {
//Variable de clase
private String ruta;
//Constructor con parametros
public Archivo(String ruta){
this.ruta = ruta;
}
//Método de clase
public String leer()throws IOException{
String contenido = "";
File archivo = null;
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try{
archivo = new File(this.ruta);
fileReader = new FileReader(archivo);
bufferedReader = new BufferedReader(fileReader);
String linea;
while((Linea = bufferedReader.readLine())!= null){
contenido += linea;
}
}
catch(Exception e){
e.prinStackTrace();
}
finally{
bufferedReader.close();
}
return contenido;
}
public void escribir (String ruta, boolean concatenar){
FileWriter archivo = null;
PrintWriter printwriter = null;
try{
archivo = new Filewriter(ruta,concatenar);
printWriter = new PrintWriter(archivo);
//for(int i=0; i<10; i++){
//printWriter = new PrintWriter(archivo);
//printWriter.println(cadena);
//}
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
archivo.close();
}catch (IOException ex){
ex.printStackTrace();
}
}
}
public void escribirObjeto(){
FileOutputStream fileOutputStream = new FileOutputStream("Persona.data");
}
catch(FileNotFoundException ex){
ex.printStackTracer();
}
catch(Exception e){
e.printStackTracer();
}
finally{
if(ObjetoOutputStream! = null){
try{
objectOutputStream.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
}
public void leerObjeto(){
FileInputStream fileInputStream = null;
ObjectInputStream objectInputStream = null;
Persona persona = new Persona();
try{
fileInputStream = new FileInputStream(ruta);
objectInputStream = new ObjectInputStream(fileInputStream);
persona = (Persona)ObjectInputStream.readObject();
}
catch(Exception e){
e.printStackTreace();
}
finally{
try{
objectInputStream.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
return persona;
}
|
package edu.pdx.advocate.dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLInput;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import javax.sql.rowset.serial.SQLInputImpl;
import oracle.jdbc.OracleTypes;
import oracle.sql.STRUCT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jdbc.support.oracle.SqlReturnSqlData;
import org.springframework.data.jdbc.support.oracle.SqlReturnStructArray;
import org.springframework.data.jdbc.support.oracle.StructMapper;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import edu.pdx.advocate.model.Course;
import edu.pdx.advocate.model.StuInfo;
public class AdvocateDao {
@Autowired
private DataSource dataSource;
public StuInfo getStudentInfo(String stuId) {
SimpleJdbcCall call = new SimpleJdbcCall(dataSource)
.withProcedureName("GetStudentInfo")
.withSchemaName("BANINST1")
.withCatalogName("ZGADVOCATE")
.declareParameters(
new SqlParameter("stuID", OracleTypes.VARCHAR))
.declareParameters(
new SqlOutParameter("stuInfo", OracleTypes.STRUCT,
"ZGADVOCATE_STUINFO_T",
new SqlReturnSqlData(StuInfo.class)));
Map<String, String> in = Collections.singletonMap("stuID", stuId);
return call.executeFunction(StuInfo.class, in);
}
public List<Course> getCourses(String stuId) {
SimpleJdbcCall call = new SimpleJdbcCall(dataSource)
.withProcedureName("GetClassSchedule")
.withSchemaName("BANINST1")
.withCatalogName("ZGADVOCATE")
.declareParameters(new SqlParameter("stuID", Types.VARCHAR))
.declareParameters(
new SqlOutParameter("classSched", Types.ARRAY,
"ZGADVOCATE_SCHED_T",
new SqlReturnStructArray<Course>(
new StructMapper<Course>() {
@Override
public Course fromStruct(STRUCT arg0)
throws SQLException {
Course course = new Course();
SQLInput input = new SQLInputImpl(
arg0.getAttributes(),
new HashMap());
course.readSQL(input,
"ZGADVOCATE_CLASS_T");
return course;
}
@Override
public STRUCT toStruct(Course arg0,
Connection arg1, String arg2)
throws SQLException {
// Not used in this case.
return null;
}
})));
Map<String, String> in = Collections.singletonMap("stuID", stuId);
Object[] courseArray = call.executeFunction(Course[].class, in);
List<Course> courses = new ArrayList<Course>();
for (Object object : courseArray) {
courses.add((Course) object);
}
return courses;
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
|
package eday1;
import java.util.Arrays;
import java.util.Scanner;
public class prim {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int V = sc.nextInt();
int E = sc.nextInt();
int[][] adj = new int[V][V];
for (int i = 0; i < E; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
adj[a][b] = c;
adj[b][a] = c;
}
boolean[] check = new boolean[V];
int[] key = new int[V];
int[] p = new int[V];
// Key의 초기값은 무한대!
Arrays.fill(key, Integer.MAX_VALUE);
// 아무거나 하나 선택!
p[0] = -1;
key[0] =0;
// 이미 하나 골랐으니 나머지 v-1개를 골라보자
for (int i = 0; i < V-1; i++) {
int min = Integer.MAX_VALUE;
// 안골라진 친구들 중에서 key가 가장 작은 친구를 뽑자
int index = -1;
for (int j = 0; j < V; j++) {
// 일단 , 안골라진지 검사, key의 최소값을 기억해야됨
if(!check[j] && key[j] < min) {
index = j;
min = key[j];
}
}
// index: 선택이 안된 정점중 key가 젤 작은 친구가 들어있다.
check[index] = true;
// index정점에서 출발하는 모든 간선에 대해서 key를 업데이트
for (int j = 0; j < V; j++) {
//check가 안되있으면서, 간선은 존재하고, 그 간선이 key값보다 작다면 키값을 업데이트
if(!check[j] && adj[index][j] != 0 && key[j] > adj[index][j]) {
//p[j] = index;
key[j] = adj[index][j];
}
}
System.out.println(Arrays.toString(key));
}
int result = 0;
for (int i = 0; i < V; i++) {
result+= key[i];
}
System.out.println(result);
//System.out.println(Arrays.toString(p));
}
}
|
package com.sample.bitnotifier.interfaces;
public interface OnDataChangeListener {
void onDataChange();
}
|
package android.support.design.widget;
import android.content.Context;
import android.graphics.Rect;
import android.support.design.widget.CoordinatorLayout.d;
import android.support.v4.view.f;
import android.support.v4.view.z;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.MeasureSpec;
import java.util.List;
abstract class HeaderScrollingViewBehavior extends ViewOffsetBehavior<View> {
private final Rect ex = new Rect();
private final Rect ey = new Rect();
int ga = 0;
int gb;
abstract View e(List<View> list);
public HeaderScrollingViewBehavior(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public boolean a(CoordinatorLayout coordinatorLayout, View view, int i, int i2, int i3, int i4) {
int i5 = view.getLayoutParams().height;
if (i5 == -1 || i5 == -2) {
View e = e(coordinatorLayout.m(view));
if (e != null) {
if (z.Z(e) && !z.Z(view)) {
z.a(view, true);
if (z.Z(view)) {
view.requestLayout();
return true;
}
}
if (z.ai(e)) {
int size = MeasureSpec.getSize(i3);
if (size == 0) {
size = coordinatorLayout.getHeight();
}
coordinatorLayout.a(view, i, i2, MeasureSpec.makeMeasureSpec(f(e) + (size - e.getMeasuredHeight()), i5 == -1 ? 1073741824 : Integer.MIN_VALUE), i4);
return true;
}
}
}
return false;
}
protected final void d(CoordinatorLayout coordinatorLayout, View view, int i) {
View e = e(coordinatorLayout.m(view));
if (e != null) {
d dVar = (d) view.getLayoutParams();
Rect rect = this.ex;
rect.set(coordinatorLayout.getPaddingLeft() + dVar.leftMargin, e.getBottom() + dVar.topMargin, (coordinatorLayout.getWidth() - coordinatorLayout.getPaddingRight()) - dVar.rightMargin, ((coordinatorLayout.getHeight() + e.getBottom()) - coordinatorLayout.getPaddingBottom()) - dVar.bottomMargin);
Rect rect2 = this.ey;
int i2 = dVar.gravity;
if (i2 == 0) {
i2 = 8388659;
}
f.apply(i2, view.getMeasuredWidth(), view.getMeasuredHeight(), rect, rect2, i);
i2 = o(e);
view.layout(rect2.left, rect2.top - i2, rect2.right, rect2.bottom - i2);
this.ga = rect2.top - e.getBottom();
return;
}
super.d(coordinatorLayout, view, i);
this.ga = 0;
}
float e(View view) {
return 1.0f;
}
final int o(View view) {
return this.gb == 0 ? 0 : n.e(Math.round(e(view) * ((float) this.gb)), 0, this.gb);
}
int f(View view) {
return view.getMeasuredHeight();
}
}
|
package day13_methods_Part1;
public class passMultipleArgument {
public static void main(String[] args) {
showSum(2,5);
showSum(20,50);
showSum(210,15);
showSum(250,55);
}
public static void showSum( int num1, int num2) {
System.out.println(num1+num2);
}
}
|
package view;
import javax.swing.JOptionPane;
/**
* @version Adreli_4_Gui_Server
* @author Jan-Hendrik Hausner
* @author John Budnik
* @author Luca Weinmann
*/
public class ServerLeaveView {
/**
*
* @return JOptionPane
*/
public int leaveServer() {
return JOptionPane.showConfirmDialog(null, "Möchten sie das Servermenü wirklich verlassen", "Servermenü verlassen", JOptionPane.YES_NO_CANCEL_OPTION);
}
}
|
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
@TeleOp(name="DriverControlled13475", group="LinearOpMode")
public class ZachsGonnaKickMeOffRobotics extends LinearOpMode {
private DcMotor rightDrive = null;
private DcMotor leftDrive = null;
private DcMotor landerRiserA = null;
private DcMotor landerRiserB = null;
private DcMotor spinnyArmExt = null;
private DcMotor spinnyArmTiltA = null;
private DcMotor spinnyArmTiltB = null;
private CRServo spinnerA = null;
private CRServo spinnerB = null;
private Servo dumperA = null;
private Servo dumperB = null;
private Servo flippy = null;
@Override
public void runOpMode() {
setUp();
boolean flipperCount= false;
int spinnerCount = 0;
while(opModeIsActive()) {
float driveLeft = gamepad1.left_stick_y;
float driveRight = gamepad1.right_stick_y;
float landerRiserpwr = gamepad1.left_trigger - gamepad1.right_trigger;
while (gamepad2.dpad_down) {
spinnyArmTiltA.setPower(-.5);
spinnyArmTiltB.setPower(-.5);
}
leftDrive.setPower(driveLeft);
rightDrive.setPower(driveRight);
landerRiserA.setPower(landerRiserpwr);
landerRiserB.setPower(landerRiserpwr);
if (gamepad2.y) {
if (flipperCount == false) {
flippy.setPosition(0);
flipperCount = true;
} else if (flipperCount == true) {
flippy.setPosition(1);
flipperCount = false;
}
}
}
}
private void setUp(){
leftDrive = hardwareMap.get(DcMotor.class, "leftDrive");
rightDrive = hardwareMap.get(DcMotor.class, "rightDrive");
landerRiserA = hardwareMap.get(DcMotor.class, "landerRiserA");
landerRiserB = hardwareMap.get(DcMotor.class, "landerRiserB");
flippy = hardwareMap.servo.get("flippy");
leftDrive.setDirection(DcMotor.Direction.FORWARD);
rightDrive.setDirection(DcMotor.Direction.REVERSE);
waitForStart();
}
} |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package LanguageWorkbenchCompetition.impl;
import LanguageWorkbenchCompetition.*;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class LanguageWorkbenchCompetitionFactoryImpl extends EFactoryImpl implements LanguageWorkbenchCompetitionFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static LanguageWorkbenchCompetitionFactory init() {
try {
LanguageWorkbenchCompetitionFactory theLanguageWorkbenchCompetitionFactory = (LanguageWorkbenchCompetitionFactory)EPackage.Registry.INSTANCE.getEFactory("http://de.htwg.2012.lwc");
if (theLanguageWorkbenchCompetitionFactory != null) {
return theLanguageWorkbenchCompetitionFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new LanguageWorkbenchCompetitionFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LanguageWorkbenchCompetitionFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case LanguageWorkbenchCompetitionPackage.LWC_MODEL_ELEMENT: return createLWCModelElement();
case LanguageWorkbenchCompetitionPackage.LWC_HEAT_EXCHANGER: return createLWCHeatExchanger();
case LanguageWorkbenchCompetitionPackage.LWC_PIPE: return createLWCPipe();
case LanguageWorkbenchCompetitionPackage.LWC_SOURCE_EXHAUST_START: return createLWCSourceExhaustStart();
case LanguageWorkbenchCompetitionPackage.LWC_VESSEL_VERTICAL: return createLWCVesselVertical();
case LanguageWorkbenchCompetitionPackage.LWC_VESSEL_HORIZONTAL: return createLWCVesselHorizontal();
case LanguageWorkbenchCompetitionPackage.LWC_VALVE: return createLWCValve();
case LanguageWorkbenchCompetitionPackage.LWC_VALVE_MANUEL: return createLWCValveManuel();
case LanguageWorkbenchCompetitionPackage.LWC_VALVE_CONTROL: return createLWCValveControl();
case LanguageWorkbenchCompetitionPackage.LWC_PUMP: return createLWCPump();
case LanguageWorkbenchCompetitionPackage.LWC_PUMP_VACUUM: return createLWCPumpVacuum();
case LanguageWorkbenchCompetitionPackage.LWC_SYSTEM_END: return createLWCSystemEnd();
case LanguageWorkbenchCompetitionPackage.LWC_JOINT: return createLWCJoint();
case LanguageWorkbenchCompetitionPackage.LWC_LOCATION_NO_LINE: return createLWCLocationNoLine();
case LanguageWorkbenchCompetitionPackage.LWC_LOCATION_SOLID_LINE: return createLWCLocationSolidLine();
case LanguageWorkbenchCompetitionPackage.LWC_LOCATION_DASH_LINE: return createLWCLocationDashLine();
case LanguageWorkbenchCompetitionPackage.LWC_SOURCE_EXHAUST_END: return createLWCSourceExhaustEnd();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCModelElement createLWCModelElement() {
LWCModelElementImpl lwcModelElement = new LWCModelElementImpl();
return lwcModelElement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCHeatExchanger createLWCHeatExchanger() {
LWCHeatExchangerImpl lwcHeatExchanger = new LWCHeatExchangerImpl();
return lwcHeatExchanger;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCPipe createLWCPipe() {
LWCPipeImpl lwcPipe = new LWCPipeImpl();
return lwcPipe;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCSourceExhaustStart createLWCSourceExhaustStart() {
LWCSourceExhaustStartImpl lwcSourceExhaustStart = new LWCSourceExhaustStartImpl();
return lwcSourceExhaustStart;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCVesselVertical createLWCVesselVertical() {
LWCVesselVerticalImpl lwcVesselVertical = new LWCVesselVerticalImpl();
return lwcVesselVertical;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCVesselHorizontal createLWCVesselHorizontal() {
LWCVesselHorizontalImpl lwcVesselHorizontal = new LWCVesselHorizontalImpl();
return lwcVesselHorizontal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCValve createLWCValve() {
LWCValveImpl lwcValve = new LWCValveImpl();
return lwcValve;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCValveManuel createLWCValveManuel() {
LWCValveManuelImpl lwcValveManuel = new LWCValveManuelImpl();
return lwcValveManuel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCValveControl createLWCValveControl() {
LWCValveControlImpl lwcValveControl = new LWCValveControlImpl();
return lwcValveControl;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCPump createLWCPump() {
LWCPumpImpl lwcPump = new LWCPumpImpl();
return lwcPump;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCPumpVacuum createLWCPumpVacuum() {
LWCPumpVacuumImpl lwcPumpVacuum = new LWCPumpVacuumImpl();
return lwcPumpVacuum;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCSystemEnd createLWCSystemEnd() {
LWCSystemEndImpl lwcSystemEnd = new LWCSystemEndImpl();
return lwcSystemEnd;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCJoint createLWCJoint() {
LWCJointImpl lwcJoint = new LWCJointImpl();
return lwcJoint;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCLocationNoLine createLWCLocationNoLine() {
LWCLocationNoLineImpl lwcLocationNoLine = new LWCLocationNoLineImpl();
return lwcLocationNoLine;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCLocationSolidLine createLWCLocationSolidLine() {
LWCLocationSolidLineImpl lwcLocationSolidLine = new LWCLocationSolidLineImpl();
return lwcLocationSolidLine;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCLocationDashLine createLWCLocationDashLine() {
LWCLocationDashLineImpl lwcLocationDashLine = new LWCLocationDashLineImpl();
return lwcLocationDashLine;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LWCSourceExhaustEnd createLWCSourceExhaustEnd() {
LWCSourceExhaustEndImpl lwcSourceExhaustEnd = new LWCSourceExhaustEndImpl();
return lwcSourceExhaustEnd;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LanguageWorkbenchCompetitionPackage getLanguageWorkbenchCompetitionPackage() {
return (LanguageWorkbenchCompetitionPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
public static LanguageWorkbenchCompetitionPackage getPackage() {
return LanguageWorkbenchCompetitionPackage.eINSTANCE;
}
} //LanguageWorkbenchCompetitionFactoryImpl
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$hv extends g {
public c$hv() {
super("setFontSizeCallback", "", -2, false);
}
}
|
/*
* Copyright 2013 Basho Technologies 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.basho.riak.client.core;
import com.basho.riak.client.core.fixture.NetworkTestFixture;
import com.basho.riak.client.core.operations.FetchOperation;
import com.basho.riak.client.core.query.Location;
import com.basho.riak.client.core.query.Namespace;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.junit.After;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author Brian Roach <roach at basho dot com>
*/
public class RiakClusterFixtureTest
{
private NetworkTestFixture[] fixtures;
@Before
public void setUp() throws IOException
{
fixtures = new NetworkTestFixture[3];
for (int i = 0, j = 5000; i < 3; i++, j += 1000)
{
fixtures[i] = new NetworkTestFixture(j);
new Thread(fixtures[i]).start();
}
}
@After
public void tearDown() throws IOException
{
for (int i = 0; i < fixtures.length; i++)
{
fixtures[i].shutdown();
}
}
@Test
public void operationSuccess() throws UnknownHostException, InterruptedException, ExecutionException
{
List<RiakNode> list = new LinkedList<RiakNode>();
for (int i = 5000; i < 8000; i += 1000)
{
RiakNode.Builder builder = new RiakNode.Builder()
.withMinConnections(10)
.withRemotePort(i + NetworkTestFixture.PB_FULL_WRITE_STAY_OPEN);
list.add(builder.build());
}
RiakCluster cluster = new RiakCluster.Builder(list).build();
cluster.start();
Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, "test_bucket");
Location location = new Location(ns, "test_key2");
FetchOperation operation =
new FetchOperation.Builder(location).build();
cluster.execute(operation);
try
{
FetchOperation.Response response = operation.get();
assertEquals(response.getObjectList().get(0).getValue().toString(), "This is a value!");
assertTrue(!response.isNotFound());
}
catch(InterruptedException e)
{
}
cluster.shutdown().get();
}
@Test
public void operationFail() throws UnknownHostException, ExecutionException, InterruptedException
{
List<RiakNode> list = new LinkedList<RiakNode>();
for (int i = 5000; i < 8000; i += 1000)
{
RiakNode.Builder builder = new RiakNode.Builder()
.withMinConnections(10)
.withRemotePort(i + NetworkTestFixture.ACCEPT_THEN_CLOSE);
list.add(builder.build());
}
RiakCluster cluster = new RiakCluster.Builder(list).build();
cluster.start();
Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, "test_bucket");
Location location = new Location(ns, "test_key2");
FetchOperation operation =
new FetchOperation.Builder(location)
.build();
cluster.execute(operation);
try
{
operation.await();
assertFalse(operation.isSuccess());
assertNotNull(operation.cause());
}
finally
{
cluster.shutdown().get();
}
}
@Test
public void testStateListener() throws UnknownHostException, InterruptedException, ExecutionException
{
List<RiakNode> list = new LinkedList<RiakNode>();
for (int i = 5000; i < 8000; i += 1000)
{
RiakNode.Builder builder = new RiakNode.Builder()
.withMinConnections(10)
.withRemotePort(i + NetworkTestFixture.PB_FULL_WRITE_STAY_OPEN);
list.add(builder.build());
}
RiakCluster cluster = new RiakCluster.Builder(list).build();
StateListener listener = new StateListener();
cluster.registerNodeStateListener(listener);
cluster.start();
// Yeah, yeah, fragile ... whatever
Thread.sleep(3000);
cluster.shutdown().get();
// Upon registering the initial node state of each node should be sent.
assertEquals(3, listener.stateCreated);
// All three nodes should go through all three states and notify.
assertEquals(3, listener.stateRunning);
assertEquals(3, listener.stateShuttingDown);
assertEquals(3, listener.stateShutdown);
}
public static class StateListener implements NodeStateListener
{
public int stateCreated;
public int stateRunning;
public int stateShuttingDown;
public int stateShutdown;
@Override
public void nodeStateChanged(RiakNode node, RiakNode.State state)
{
switch(state)
{
case CREATED:
stateCreated++;
break;
case RUNNING:
stateRunning++;
break;
case SHUTTING_DOWN:
stateShuttingDown++;
break;
case SHUTDOWN:
stateShutdown++;
break;
default:
break;
}
}
}
}
|
package framework.commands;
public interface Invoker {
public void setCommand(Command command);
public void invokeCommand();
}
|
package com.mhsn.linkedList.duplicate;
import com.mhsn.linkedList.LinkedListUtils;
import com.mhsn.linkedList.MyLinkedList;
import com.mhsn.linkedList.Node;
public class RemoveDuplicatesFromSortedList {
public static Node removeDuplicatefromSortedList(Node head){
Node current = head;
while(current !=null && current.next !=null){
Node temp = current.next.next;
if(current.value == current.next.value)
current.next = temp;
if(temp == null)
break;
if(current.value != current.next.value)
current = current.next;
}
return null;
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.addNode(1); list.addNode(1); list.addNode(2); list.addNode(3);
list.addNode(4); list.addNode(4); list.addNode(5); list.addNode(5);
list.addNode(6);
LinkedListUtils.printLink(list.head);
removeDuplicatefromSortedList(list.head);
LinkedListUtils.printLink(list.head);
}
}
|
package test.abcd.pierwszaAplikacja;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication()
public class PierwszaApplication {
public static void main(String[] args) {
SpringApplication.run(PierwszaApplication.class, args);
}
}
|
package com.springboot.quickstart.controller;
import com.springboot.quickstart.pojo.Orders;
import com.springboot.quickstart.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* class_name: OrdersController
* package: com.springboot.quickstart.controller
* describe: TODO
* @author: Liuxianglong
* @date: 2018/1/20
* creat_time: 19:44
**/
@Controller
public class OrdersController {
@Autowired
private OrdersService ordersService;
@RequestMapping("/orders/{id}")
@ResponseBody
public Orders getOrders(@PathVariable Integer id){
return ordersService.selectById(id);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package TallerPoo;
import java.awt.Color;
import java.util.Objects;
public class TipoCuidado {
private Boolean tapabocas, distanciamiento, desinfectar, evitarcontacto;
public TipoCuidado(Boolean tapabocas, Boolean distanciamiento, Boolean desinfectar, Boolean evitarcontacto) {
this.tapabocas = tapabocas;
this.distanciamiento = distanciamiento;
this.desinfectar = desinfectar;
this.evitarcontacto = evitarcontacto;
}
/*
* return @tapabocas
*/
public Boolean getTapabocas() {
return tapabocas;
}
/*
* set @tapabocas
*/
public void setTapabocas(Boolean tapabocas) {
this.tapabocas = tapabocas;
}
/*
* return @distanciamiento
*/
public Boolean getDistanciamiento() {
return distanciamiento;
}
/*
* set @distanciamiento
*/
public void setDistanciamiento(Boolean distanciamiento) {
this.distanciamiento = distanciamiento;
}
/*
* return @desinfectar
*/
public Boolean getDesinfectar() {
return desinfectar;
}
/*
* set @desinfectar
*/
public void setDesinfectar(Boolean desinfectar) {
this.desinfectar = desinfectar;
}
/*
* return @evitarcontacto
*/
public Boolean getEvitarcontacto() {
return evitarcontacto;
}
/*
* set @evitarcontacto
*/
public void setEvitarcontacto(Boolean evitarcontacto) {
this.evitarcontacto = evitarcontacto;
}
@Override
public int hashCode() {
int hash = 7;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TipoCuidado other = (TipoCuidado) obj;
if (!Objects.equals(this.tapabocas, other.tapabocas)) {
return false;
}
if (!Objects.equals(this.distanciamiento, other.distanciamiento)) {
return false;
}
if (!Objects.equals(this.desinfectar, other.desinfectar)) {
return false;
}
if (!Objects.equals(this.evitarcontacto, other.evitarcontacto)) {
return false;
}
return true;
}
/**
* da el color a cada persona según el tipo de cuidado que esta tenga
*
* @return Colore
*/
public Color tipoCuidado() {
if (tapabocas && distanciamiento && desinfectar && evitarcontacto) {
return Color.GREEN;
} else if (tapabocas) {
return Color.YELLOW;
} else if (!(tapabocas && distanciamiento && desinfectar && evitarcontacto)) {
return Color.ORANGE;
}
return Color.ORANGE;
}
}
|
package accounts.Client;
import accounts.entity.AccountsEntity;
import accounts.operations.AccountsOperations;
import operations.implementations.AccountsOperationsImplementations;
public class AccountsClient {
public static void main(String[] args) {
AccountsEntity customer=new AccountsEntity(5000000, 2038087654, "sudhanshu", "Bhopal");
AccountsOperationsImplementations obj=new AccountsOperationsImplementations(10, 50000,customer,customer.getBalance());
System.out.println(obj.calculateAmount(obj.getRateOfInterest(),5));
System.out.println(obj.display(customer.getBalance()));
System.out.println(obj.withdrawal(30000));
System.out.println(obj.deposit(40000));
}
}
|
package com.mygdx.game.components;
public class RemoveIfOffScreenComponent {
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package overlay;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.security.auth.login.Configuration;
import overlay.actions.Action;
import overlay.actions.LookUp;
import overlay.actions.Put;
import overlay.vcube.VCubeCreate;
import overlay.vcube.VCubeProtocol;
import peersim.core.CommonState;
import peersim.core.Network;
import peersim.core.Node;
import peersim.core.Protocol;
import peersim.edsim.EDSimulator;
import peersim.transport.Transport;
/**
*
* @author elixandrebaldi
*/
public class Utils {
static public boolean flagDown = true;
static public int pid = 0;
public static long hitsLookup = 0;
public static long hitsPut = 0;
public static long countUpQueue = 0;
public static long countUpStatusTrue = 0;
public static long countTestesVCube = 0;
public static boolean flagPut = true;
public static boolean flagLookup = true;
public static int nPuts = 900000;
public static long sumTimePut = 0;
public static long countPuts = 0;
public static long sumTimeLookup = 0;
public static long countLookup = 0;
public static long nLookups = 3000000;
public static int timeNewEvent = 0;
public static long timeDiagnostic = 0;
public static int countDiagnostic = 0;
public static int timeEnd = 100000000;
public static int countLookupFault = 0;
public static int countPutFault = 0;
public static int countRePut = 0;
public static int countReLookup = 0;
public static int countExitNode = 0;
public static int countStartNode = 0;
public static int countPutSend = 0;
public static int countViewFull = 0;
public static int countDelegateFindMostAppropriate = 0;
public static int countSumTimeUp = 0;
public static int sumTimeUp = 0;
public static int stepVCube = 0;
public static int getRepeatNextEvent() {
int now = CommonState.getIntTime();
int div = now % Utils.stepVCube;
return Utils.stepVCube - div;
}
public static void finish(int time) {
try(FileWriter fw = new FileWriter(VCubeCreate.pathOut, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
if(VCubeCreate.scenario == 0) {
out.println(countTestesVCube+";"+countUpStatusTrue+";"+countDelegateFindMostAppropriate+";"+countViewFull+";"+time+";");
} else if(VCubeCreate.scenario == 1 || VCubeCreate.scenario == 2) {
long countPutsTrue = countPuts - countPutFault;
long mediaPuts = countPutsTrue/sumTimePut;
out.println(countTestesVCube+";"+sumTimePut+";"+countPutsTrue+";"+mediaPuts+";"+countRePut+";"+time);
} else if(VCubeCreate.scenario == 3 || VCubeCreate.scenario == 4) {
long countLookUpTrue = countLookup - countLookupFault;
long mediaLookup = sumTimeLookup/countLookUpTrue;
out.println(countTestesVCube+";"+sumTimeLookup+";"+countLookUpTrue+";"+mediaLookup+";"+countReLookup+";"+time);
} else if(VCubeCreate.scenario == 5) {
long countPutsTrue = countPuts - countPutFault;
long mediaPuts = sumTimePut/countPutsTrue;
out.println(countTestesVCube+";"+sumTimePut+";"+countPutsTrue+";"+mediaPuts+";"+countRePut+";"+countUpStatusTrue+";"+timeDiagnostic+";"+time);
} else if(VCubeCreate.scenario == 6) {
long countLookUpTrue = countLookup - countLookupFault;
long mediaLookup = sumTimeLookup/countLookUpTrue;
out.println(countTestesVCube+";"+sumTimeLookup+";"+countLookUpTrue+";"+mediaLookup+";"+countReLookup+";"+countUpStatusTrue+";"+timeDiagnostic+";"+time);
} else if(VCubeCreate.scenario == 7) {
long countPutsTrue = countPuts - countPutFault;
long mediaPuts = sumTimePut/countPutsTrue;
out.println(countTestesVCube+";"+sumTimePut+";"+countPutsTrue+";"+mediaPuts+";"+countRePut+";"+countUpStatusTrue+";"+countStartNode+";"+countExitNode+";"+time);
} else if(VCubeCreate.scenario == 8) {
long countLookUpTrue = countLookup - countLookupFault;
long mediaLookup = sumTimeLookup/countLookUpTrue;
out.println(countTestesVCube+";"+sumTimeLookup+";"+countLookUpTrue+";"+mediaLookup+";"+countReLookup+";"+countUpStatusTrue+";"+timeDiagnostic+";"+countStartNode+";"+countExitNode+";"+time);
}
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
/*System.out.println("Quantidade de Hits - Put: ");
System.out.println("Quantidade de tentativas de acionar um nodo já ativo: ");
System.out.println("Quantidade de Testes do VCube: ");
System.out.println("Tempo Final: ");*/
System.exit(0);
}
static public void updateTimestampLocal(short[] timestampLocal, short[] timestampSender, int indexLocal, int indexSender) {
for(int i = 0; i < timestampLocal.length; i++) {
if(timestampLocal[i] < timestampSender[i] && i != indexLocal) {
timestampLocal[i] = timestampSender[i];
if(timestampLocal[i] % 2 != 0) {
//System.out.println("Diagnóstico "+indexLocal);
Utils.timeDiagnostic = CommonState.getIntTime();
}
}
}
if(timestampLocal[indexSender] % 2 != 0) timestampLocal[indexSender]++;
}
static public short findResponsible(short v, short[] timestamp) {
short z = 0;
short i = v;
while(true){
if(i < Network.size() && timestamp[i]%2 == 0) break;
z++;
i = (short) (v^z);
}
/* System.out.println("Encontrado "+i);
for(int j = 0; j < timestamp.length; j++){
System.out.print(timestamp[j]+", ");
}
System.out.println("");*/
return i;
}
static public short responsibleKey(byte[] hash, short[] timestamp) {
BigInteger value = new BigInteger(hash);
BigInteger two = new BigInteger("2");
BigInteger v = value.divide(two.pow(256-VCubeCreate.getnCluster()));
short j = v.shortValue();
if(j < 0) j *= -1;
//TODO ta certo esse * -1?
return findResponsible(j, timestamp);
//return j;
}
static public Node getRandomNode() {
Node target;
short size = (short) Network.size();
VCubeProtocol protocol = null;
do{
target = Network.get(CommonState.r.nextInt(size));
protocol = (VCubeProtocol) target.getProtocol(Utils.pid);;
} while(target == null || !protocol.getStatus());
return target;
}
public static byte[] generateHash(String resource, String algorithm) {
try {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(resource.getBytes());
return md.digest();
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static String stringHexa(byte[] bytes) {
StringBuilder s = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
int highPiece = ((bytes[i] >> 4) & 0xf) << 4;
int lowPiece = bytes[i] & 0xf;
if (highPiece == 0) s.append('0');
s.append(Integer.toHexString(highPiece | lowPiece));
}
return s.toString();
}
public static String getRandomString() {
byte[] array = new byte[20]; // length is bounded by 7
new Random().nextBytes(array);
return new String(array, Charset.forName("UTF-8"));
}
public static void executeLookup(byte[] hash, Node node, VCubeProtocol protocol){
short p = Utils.responsibleKey(hash, protocol.getTimestamp().clone());
int time = CommonState.getIntTime();
EDSimulator.add(1, new LookUp(node.getIndex(), hash, time), Network.get(p), Utils.pid);
//System.out.println("Nodo "+protocol.getCurrentId()+" enviando lookup para "+p);
}
public static void executeReLookup(byte[] hash, Node node, VCubeProtocol protocol){
short p = Utils.responsibleKey(hash, protocol.getTimestamp().clone());
int time = CommonState.getIntTime();
EDSimulator.add(Utils.getRepeatNextEvent(), new LookUp(node.getIndex(), hash, time), Network.get(p), Utils.pid);
//System.out.println("Nodo "+protocol.getCurrentId()+" reenviando lookup para "+p+" time: "+time);
}
public static void executePut(byte[] hash, Node node, VCubeProtocol protocol) {
short p = Utils.responsibleKey(hash, protocol.getTimestamp().clone());
int time = CommonState.getIntTime();
EDSimulator.add(1, new Put(node.getIndex(), hash, time), Network.get(p), Utils.pid);
//System.out.println("Nodo "+protocol.getCurrentId()+" enviando put para "+p);
}
public static void executeRePut(byte[] hash, Node node, VCubeProtocol protocol) {
short p = Utils.responsibleKey(hash, protocol.getTimestamp().clone());
int time = CommonState.getIntTime();
EDSimulator.add(Utils.getRepeatNextEvent(), new Put(node.getIndex(), hash, time), Network.get(p), Utils.pid);
//System.out.println("Nodo "+protocol.getCurrentId()+" enviando put para "+p);
}
public static void printNetwork() {
for(int i = 0; i < Network.size(); i++) {
VCubeProtocol node = (VCubeProtocol) Network.get(i).getProtocol(Utils.pid);
System.out.print(" "+node.getStatus());
}
System.out.println("");
}
public static int getIndexResponsable(short responsable, List<Responsables> responsables) {
for(int i = 0; i < responsables.size(); i++) {
if(responsables.get(i).getResponsable() == responsable) return i;
}
return -1;
}
public static short findFuller(short[] timestamp){
short fuller = -1;
int countFuller = -1;
List<Responsables> responsables = new ArrayList<>();
for(int i = 0; i < timestamp.length; i++) {
if(timestamp[i] % 2 != 0 ){
short responsable = Utils.findResponsible((short) i, timestamp);
int indexResponsable = getIndexResponsable(responsable, responsables);
if( indexResponsable >= 0) {
int count = responsables.get(indexResponsable).incrementCount();
if(count > countFuller) {
fuller = responsable;
countFuller = count;
}
} else {
responsables.add(new Responsables(responsable));
if(countFuller < 1) {
fuller = responsable;
countFuller = 1;
}
}
}
}
return fuller;
}
public static boolean isPair(short s) {
return s % 2 == 0;
}
public static boolean networkFull() {
for(int i = 0; i < Network.size(); i++) {
VCubeProtocol protocol = (VCubeProtocol) Network.get(i).getProtocol(Utils.pid);
if(!protocol.getStatus()) {
return false;
}
}
return true;
}
public static boolean canDown() {
int count = 0;
int size = Network.size();
for(int i = 0; i < size; i++) {
VCubeProtocol protocol = (VCubeProtocol) Network.get(i).getProtocol(Utils.pid);
if(protocol.getStatus()) count++;
}
//System.out.println("can Down: "+count);
if(count >= size * 0.3) return true;
return false;
}
public static long countNodesOff() {
int count = 0;
for(int i = 0; i < Network.size(); i++) {
VCubeProtocol protocol = (VCubeProtocol) Network.get(i).getProtocol(Utils.pid);
if(!protocol.getStatus()) count++;
}
return count;
}
}
|
package com.kingdee.lightapp.service.openorg.impl;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kingdee.lightapp.common.constants.LightappURLConstants;
import com.kingdee.lightapp.oauth.OAuth;
import com.kingdee.lightapp.oauth.Parameter;
import com.kingdee.lightapp.service.LightappConfigureService;
import com.kingdee.lightapp.service.openorg.OpenorgService;
import com.kingdee.lightapp.utils.HttpClientHelper;
import com.kingdee.lightapp.utils.MapUtils;
@Service
public class OpenorgServiceImpl implements OpenorgService{
private static final Logger LOGGER = LoggerFactory.getLogger(OpenorgServiceImpl.class);
@Autowired
private LightappConfigureService lightAppConfigureService;
private String getOrgInfoBy(String consumerKey,
String consumerSecret, String userAgent, JSONObject params,String requestUrl){
String METHON="POST";
if(requestUrl.contains("/get/")){
METHON="GET";
}
OAuth oAuth = new OAuth(consumerKey, consumerSecret,"");
Parameter[] requestParams= Parameter.convertJSON2ParameterArray(params);
String authorization =oAuth.generateAuthorizationHeader(METHON, requestUrl,requestParams, null);
Map<String, String> headers=new HashMap<String, String>();
if (StringUtils.isNotBlank(authorization)) {
headers.put("Authorization", authorization);
}
headers.put("User-Agent", userAgent);
/* headers.put("appId", consumerKey);*/
try {
return HttpClientHelper.postForm(requestUrl, MapUtils.toHashMap(params), headers, 3000, 5000);
} catch (Exception e) {
LOGGER.error(e.getMessage(),e);
}
return "";
}
@Override
public String getPersonInfoByEidAndOpenId(String userAgent,String openIds ,String eId){
String consumerKey=lightAppConfigureService.getMcloudAppId();
String consumerSecret=lightAppConfigureService.getMcloudAppSecret();
String requestUrl=lightAppConfigureService.getKdweiboHost()+LightappURLConstants.OPENID_GET_PERSON;
JSONObject params=new JSONObject();
params.put("openIds", openIds);
params.put("eid", eId);
return getOrgInfoBy(consumerKey, consumerSecret, userAgent, params, requestUrl);
}
}
|
package com.sanlitec.test1;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import java.lang.reflect.ReflectPermission;
/**
* Created by sanlitec on 2016/9/27.
*/
public class TestSvr extends Service {
@Override
public void onCreate() {
super.onCreate();
Log.i(this.getClass().getName(),"Create");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(this.getClass().getName(),"StartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i(this.getClass().getName(),"Destory");
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i(this.getClass().getName(),"Bind");
return new TestBinder();
}
class TestBinder extends Binder {
public void startMethod() {
Log.i(this.getClass().getName(), "startMethod() executed");
// 执行具体的下载任务
}
TestSvr getService() {
// Return this instance of LocalService so clients can call public methods
return TestSvr.this;
}
}
}
|
package by.tc.task01.dao.impl;
import by.tc.task01.dao.AbstractFileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import java.util.stream.Collectors;
class TextFileReader extends AbstractFileReader {
private final BufferedReader reader;
TextFileReader(String path) throws FileNotFoundException {
super(path);
reader = new BufferedReader(new FileReader(path));
}
public List<String> linesList() {
return reader.lines().collect(Collectors.toList());
}
}
|
package com.youtalkwesign.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.language.v1.AnalyzeSyntaxRequest;
import com.google.cloud.language.v1.AnalyzeSyntaxResponse;
import com.google.cloud.language.v1.Document;
import com.google.cloud.language.v1.Document.Type;
import com.google.cloud.language.v1.EncodingType;
import com.google.cloud.language.v1.LanguageServiceClient;
import com.google.cloud.language.v1.LanguageServiceSettings;
import com.google.cloud.language.v1.Token;
import com.youtalkwesign.model.Text;
import com.youtalkwesign.model.Transcript;
import com.youtalkwesign.model.Word;
import com.youtalkwesign.repository.WordRepository;
@Service
public class MainService {
@Autowired
WordRepository wordRepo;
public List<Text> getTranscript(String v) {
JAXBContext jc = null;
Transcript root = null;
try {
String uri = "http://video.google.com/timedtext?lang=en&v=" + v;
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
InputStream xml = connection.getInputStream();
jc = JAXBContext.newInstance(Transcript.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
root = (Transcript) unmarshaller.unmarshal(xml);
} catch (JAXBException e) {
} catch (MalformedURLException e) {
} catch (ProtocolException e) {
} catch (IOException e) {
}
// initialize texts
List<Text> newTexts = new ArrayList<Text>();
if (root != null) {
// get transcript
List<Text> currentTexts = root.getTexts();
for (int i = 0; i < currentTexts.size(); i++) {
String text = currentTexts.get(i).getText();
text = text.replace("'", "'"); // it is ' character
text = text.replaceAll("[\\p{Punct}&&[^'-]]+", " "); // remove punctuations except ' and -
text = text.toLowerCase();
text = text.replace("ı", "i");
text = text.replaceAll("[\\t\\n\\r]+"," "); // replace new lines with spaces
text = text.trim().replaceAll(" +", " "); // replace more than one spaces with one
text = text.replace("'m", " am");
text = text.replace("'s", " is");
text = text.replace("'re", " are");
text = text.replace("'ve", " have");
text = text.replace("'ll", " will");
text = text.replace("'d", " would");
text = text.replace("can't", "cannot");
text = text.replace("n't", " not");
text = text.replace("let's", "let us");
text = text.replace("'", "");
text = text.replace("quot", "");
text = text.trim().replaceAll(" +", " "); // replace more than one spaces with one
if (text.length() > 0) {
if (text.charAt(0) == ' ') {
text = text.substring(1);
}
}
Text temp = new Text();
// set start
String start = currentTexts.get(i).getStart();
temp.setStart(currentTexts.get(i).getStart());
// set duration
if (i != currentTexts.size() - 1) {
String nextStart = currentTexts.get(i + 1).getStart();
double startDouble = Double.parseDouble(start);
double nextStartDouble = Double.parseDouble(nextStart);
double newDurDouble = nextStartDouble - startDouble;
temp.setDur("" + newDurDouble);
} else {
temp.setDur(currentTexts.get(i).getDur());
}
// set text
temp.setText(text);
newTexts.add(temp);
}
}
// get simple forms
List<Text> simpleTexts = getSimpleForms(newTexts);
// return
return simpleTexts;
}
public List<Word> getWords(List<Text> texts) {
// initialize helper set
Set<String> wordSet = new HashSet<String>();
for (int i = 0; i < texts.size(); i++) {
// get text and delete commas and dots
String text = texts.get(i).getText();
// split text into words
String[] words = text.split("\\s+");
for (int j = 0; j < words.length; j++) {
// You may want to check for a non-word character before blindly
// performing a replacement
// It may also be necessary to adjust the character class
words[j] = words[j].replaceAll("[^\\w]", "");
}
// add each word to list with the corresponding video url
for (int k = 0; k < words.length; k++) {
String word = words[k];
wordSet.add(word);
}
}
// get word set from the database and
// convert iterable to array list
Iterable<Word> source = wordRepo.findAll(wordSet);
List<Word> target = new ArrayList<Word>();
source.forEach(word -> {
word.setVideoUrl("sign-videos/" + word.getWord() + ".mp4");
target.add(word);
});
return target;
}
private List<Text> getSimpleForms(List<Text> texts) {
// initialize result
List<Text> result = new ArrayList<Text>();
// initialize list
String lines = "";
for (Text text : texts) {
lines = lines + text.getText() + " LINEBREAK ";
}
List<String> simpleLines = new ArrayList<String>();
GoogleCredentials credentials;
LanguageServiceSettings settings;
File credentialsPath = new File("D:/service-account-file.json");
// TODO: D:/service-account-file.json OR /home/service-account-file.json
try (FileInputStream serviceAccountStream = new FileInputStream(credentialsPath)) {
credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
FixedCredentialsProvider credentialsProvider = FixedCredentialsProvider.create(credentials);
settings = LanguageServiceSettings.newBuilder()
.setCredentialsProvider(credentialsProvider)
.build();
LanguageServiceClient language = LanguageServiceClient.create(settings);
Document doc = Document.newBuilder()
.setContent(lines)
.setType(Type.PLAIN_TEXT)
.build();
AnalyzeSyntaxRequest request = AnalyzeSyntaxRequest.newBuilder()
.setDocument(doc)
.setEncodingType(EncodingType.UTF16)
.build();
// analyze the syntax in the given text
AnalyzeSyntaxResponse response = language.analyzeSyntax(request);
// response
for (Token token : response.getTokensList()) {
simpleLines.add(token.getLemma());
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
String fullTranscript = "";
for (String line : simpleLines) {
fullTranscript = fullTranscript + line + " ";
}
// split them according to LINEBREAK sentinel value
List<String> updatedLines =
new ArrayList<String>(Arrays.asList(fullTranscript.split("LINEBREAK")));
// update texts and add it to result
for (int i = 0; i < texts.size(); i++) {
Text text = texts.get(i);
String updated = updatedLines.get(i);
updated = updated.replace("--", ""); // remove dashes
updated = updated.replaceFirst("^\\s*", ""); // remove front spaces from lines
updated = updated.replaceAll("\\s+$", ""); // remove end spaces from lines
text.setText(updated);
result.add(text);
}
return result;
}
}
|
package de.uniba.dsg.jaxrs;
import de.uniba.dsg.jaxrs.controller.CustomerController;
import de.uniba.dsg.jaxrs.resources.SwaggerUI;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.util.*;
@ApplicationPath("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ExamplesApi extends Application {
@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> resources = new HashSet<>();
resources.add(CustomerController.class);
resources.add(SwaggerUI.class);
return resources;
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* RDeptFunctionId generated by hbm2java
*/
public class RDeptFunctionId implements java.io.Serializable {
private String deptid;
private String servicedeptid;
private String functionid;
private String employeeid;
public RDeptFunctionId() {
}
public RDeptFunctionId(String deptid, String servicedeptid, String functionid, String employeeid) {
this.deptid = deptid;
this.servicedeptid = servicedeptid;
this.functionid = functionid;
this.employeeid = employeeid;
}
public String getDeptid() {
return this.deptid;
}
public void setDeptid(String deptid) {
this.deptid = deptid;
}
public String getServicedeptid() {
return this.servicedeptid;
}
public void setServicedeptid(String servicedeptid) {
this.servicedeptid = servicedeptid;
}
public String getFunctionid() {
return this.functionid;
}
public void setFunctionid(String functionid) {
this.functionid = functionid;
}
public String getEmployeeid() {
return this.employeeid;
}
public void setEmployeeid(String employeeid) {
this.employeeid = employeeid;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof RDeptFunctionId))
return false;
RDeptFunctionId castOther = (RDeptFunctionId) other;
return ((this.getDeptid() == castOther.getDeptid()) || (this.getDeptid() != null
&& castOther.getDeptid() != null && this.getDeptid().equals(castOther.getDeptid())))
&& ((this.getServicedeptid() == castOther.getServicedeptid())
|| (this.getServicedeptid() != null && castOther.getServicedeptid() != null
&& this.getServicedeptid().equals(castOther.getServicedeptid())))
&& ((this.getFunctionid() == castOther.getFunctionid()) || (this.getFunctionid() != null
&& castOther.getFunctionid() != null && this.getFunctionid().equals(castOther.getFunctionid())))
&& ((this.getEmployeeid() == castOther.getEmployeeid())
|| (this.getEmployeeid() != null && castOther.getEmployeeid() != null
&& this.getEmployeeid().equals(castOther.getEmployeeid())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getDeptid() == null ? 0 : this.getDeptid().hashCode());
result = 37 * result + (getServicedeptid() == null ? 0 : this.getServicedeptid().hashCode());
result = 37 * result + (getFunctionid() == null ? 0 : this.getFunctionid().hashCode());
result = 37 * result + (getEmployeeid() == null ? 0 : this.getEmployeeid().hashCode());
return result;
}
}
|
/* Write this concrete (non-abstract) class called Cylinder that extends Prism.
* It has a private field (radius) and inherits its height from its superclass, Prism
* (because all prisms have a height).
* Provide a constructor and the methods required by its abstract superclass.
*/
/**
* calculates the perimeter and area of the base of a cylinder
* @author Derfel Terciano
* @version 0.1
*/
public class Cylinder extends Prism {
private double radius;
final double pi = 3.14159265359;
public Cylinder(double radius,int height) {
super(height);
this.radius=radius;
}
public double calcPerimeter() {
return 2*pi*radius;
}
public double calcAreaOfBase() {
return super.round2(pi * (radius*radius));
}
}
|
package com.websharp.dwtz.activity.main;
import java.io.File;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import com.dh.Demo.TestDpsdkCoreActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.websharp.dwtz.R;
import com.websharp.dwtz.R.id;
import com.websharp.dwtz.R.layout;
import com.websharp.dwtz.R.menu;
import com.websharp.dwtz.activity.BaseActivity;
import com.websharp.dwtz.activity.apply.ActivityAddDsitributionChangeApply;
import com.websharp.dwtz.activity.apply.ActivityApplyList;
import com.websharp.dwtz.activity.dwtzjysb.ActivityDwtzjysbList;
import com.websharp.dwtz.activity.user.ActivityCategory;
import com.websharp.dwtz.activity.user.ActivityCategoryDwtzjysb;
import com.websharp.dwtz.activity.user.ActivityLogin;
import com.websharp.dwtz.activity.web.ActivityWebview;
import com.websharp.dwtz.adapter.AdapterMainList;
import com.websharp.dwtz.adapter.AdapterOrderList;
import com.websharp.dwtz.dao.EntityButchery;
import com.websharp.dwtz.dao.EntityCommonData;
import com.websharp.dwtz.dao.EntityLocation;
import com.websharp.dwtz.dao.EntityModule;
import com.websharp.dwtz.data.Constant;
import com.websharp.dwtz.data.GlobalData;
import com.websharp.dwtz.http.AsyncHttpCallBack;
import com.websharp.dwtz.http.SJECHttpHandler;
import com.websharputil.common.AppData;
import com.websharputil.common.LogUtil;
import com.websharputil.common.PrefUtil;
import com.websharputil.common.Util;
import com.websharputil.file.FileUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings.Global;
import android.text.TextPaint;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class MainActivity extends BaseActivity {
private ImageView iv_ycspglxt;
private ImageView iv_sjxxxt;
private ImageView iv_fxxt;
private ImageView iv_sy;
private ImageView iv_whhcljgxt;
private ImageView iv_tzc;
// private ViewFlipper notice_flipper;
private PullToRefreshListView lv_content;
private AdapterMainList adapterMainList;
public RelativeLayout layout_head_title;
public TextView tv_head_title;
public TextView tv_notice;
public TextView tv_login;
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
long downloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
validDownloadStatus(downloadID);
}
}
};
@Override
public void initLayout() {
// TODO Auto-generated method stub
setContentView(R.layout.activity_main);
if (!new File(Constant.SAVE_PATH).exists()) {
new File(Constant.SAVE_PATH).mkdirs();
new File(Constant.SDCARD_ATTACH_DIR).mkdirs();
new File(Constant.SDCARD_IMAGE_DIR).mkdirs();
}
}
@Override
public void init() {
// TODO Auto-generated method stub
// tv_notice = (TextView)findViewById(R.id.tv_content);
IntentFilter filter = new IntentFilter();
filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(receiver, filter);
tv_login = (TextView) findViewById(R.id.tv_login);
iv_tzc = (ImageView) findViewById(R.id.iv_tzc);
iv_ycspglxt = (ImageView) findViewById(R.id.iv_ycspglxt);
iv_sjxxxt = (ImageView) findViewById(R.id.iv_sjxxxt);
iv_fxxt = (ImageView) findViewById(R.id.iv_fxxt);
iv_sy = (ImageView) findViewById(R.id.iv_sy);
iv_whhcljgxt = (ImageView) findViewById(R.id.iv_whhcljgxt);
// notice_flipper = (ViewFlipper)findViewById(R.id.notice_flipper);
lv_content = (PullToRefreshListView) findViewById(R.id.lv_content);
// 绑定headview
LayoutInflater mInflater = LayoutInflater.from(this);
View headView = mInflater.inflate(R.layout.headview_main, null);
layout_head_title = (RelativeLayout) headView.findViewById(R.id.layout_head_title);
tv_head_title = (TextView) headView.findViewById(R.id.tv_head_title);
tv_notice = (TextView) headView.findViewById(R.id.tv_notice);
lv_content.getRefreshableView().addHeaderView(headView);
layout_head_title.setOnClickListener(this);
tv_login.setOnClickListener(this);
tv_notice.setOnClickListener(this);
iv_tzc.setOnClickListener(this);
iv_ycspglxt.setOnClickListener(this);
iv_sjxxxt.setOnClickListener(this);
iv_fxxt.setOnClickListener(this);
iv_sy.setOnClickListener(this);
iv_whhcljgxt.setOnClickListener(this);
}
@Override
public void bindData() {
initParam();
// ImageView iv_icon = (ImageView)findViewById(R.id.iv_icon);
adapterMainList = new AdapterMainList(lv_content, this);
// TODO Auto-generated method stub
checkUpdateApk(this);
new SJECHttpHandler(cbGetModule, this).GetUserModuleByUserID();
if (GlobalData.listCommonData.size() == 0) {
new SJECHttpHandler(cbGetCommonData, MainActivity.this).getCommonData();
}
if (GlobalData.listProvince.size() == 0) {
new SJECHttpHandler(cbLocation, MainActivity.this).GetLocation();
}
if (GlobalData.listButchery.size() == 0) {
new SJECHttpHandler(cbButchery, MainActivity.this).getAllButchery();
}
if (new File(Constant.IMAGE_DIR_TAKE_PHOTO).exists()) {
FileUtil.DeleteDirectory(new File(Constant.IMAGE_DIR_TAKE_PHOTO));
}
new SJECHttpHandler(cbGetButchery, this).getButchery();
}
@Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (GlobalData.curUser == null) {
tv_login.setText("登录");
} else {
tv_login.setText(GlobalData.curUser.UserName + " 注销");
}
}
@Override
public void onClick(View v) {
Bundle b = new Bundle();
switch (v.getId()) {
case R.id.iv_tzc:
if (GlobalData.curUser == null) {
Util.startActivity(MainActivity.this, ActivityLogin.class, false);
} else {
// qytzgl
// 监管,销毁,官方兽医
// 进场登记表
// 销毁记录表
// 动物屠宰检疫申报单
// 动物产品分销换证申请表
// 统计图
// if (GlobalData.curUser.Role.equals("JG") ||
// GlobalData.curUser.Role.equals("XH")
// || GlobalData.curUser.Role.equals("GFSY")
// || GlobalData.curUser.Role.toUpperCase().equals("QYTZGL")) {
// Util.startActivity(MainActivity.this, ActivityCategory.class,
// false);
// } else {
// Util.createToast(MainActivity.this,
// R.string.msg_dialog_role_failed, 3000).show();
// }
if (GlobalData.ContainModule("进场登记表") || GlobalData.ContainModule("销毁记录表")
|| GlobalData.ContainModule("统计图")) {
Util.startActivity(MainActivity.this, ActivityCategory.class, false);
} else {
Util.createToast(MainActivity.this, R.string.msg_dialog_role_failed, 3000).show();
}
}
break;
case R.id.iv_ycspglxt:
if (GlobalData.curUser == null) {
Util.startActivity(MainActivity.this, ActivityLogin.class, false);
} else {
if (GlobalData.curUser.Role.equals("JG")) {
Util.startActivity(MainActivity.this, TestDpsdkCoreActivity.class, false);
} else {
Util.createToast(MainActivity.this, R.string.msg_dialog_role_failed, 3000).show();
}
}
break;
case R.id.iv_fxxt:
// 分销系统
if (GlobalData.curUser == null) {
Util.startActivity(MainActivity.this, ActivityLogin.class, false);
} else {
// if (GlobalData.curUser.Role.equals("FX")) {
// Util.startActivity(MainActivity.this, ActivityApplyList.class, false);
// } else {
// Util.createToast(MainActivity.this, R.string.msg_dialog_role_failed, 3000).show();
// }
if (GlobalData.ContainModule("动物产品分销换证申请表")) {
Util.startActivity(MainActivity.this, ActivityApplyList.class, false);
} else {
Util.createToast(MainActivity.this, R.string.msg_dialog_role_failed, 3000).show();
}
}
break;
case R.id.iv_sjxxxt:
// 检疫申报
// Util.startActivity(MainActivity.this, ActivityDwtzjysbList.class,
// false);
// if (!GlobalData.curUser.Role.equals("JG")) {
// Util.startActivity(MainActivity.this, ActivityDwtzjysbList.class, false);
// } else {
// Util.createToast(MainActivity.this, R.string.msg_dialog_role_failed, 3000).show();
// }
if (GlobalData.curUser == null) {
Util.startActivity(MainActivity.this, ActivityLogin.class, false);
return;
}
if (GlobalData.ContainModule("动物屠宰检疫申报单")) {
Util.startActivity(MainActivity.this, ActivityCategoryDwtzjysb.class, false);
} else {
Util.createToast(MainActivity.this, R.string.msg_dialog_role_failed, 3000).show();
}
break;
case R.id.iv_sy:
// Util.startActivity(MainActivity.this, ActivityLogin.class,
// false);
break;
case R.id.iv_whhcljgxt:
// Util.startActivity(MainActivity.this, ActivityLogin.class,
// false);
break;
case R.id.layout_head_title:
b.putString("title", getText(tv_head_title));
b.putString("url",
String.format(SJECHttpHandler.URL_PAGE_ARTICLE_CONTENT, layout_head_title.getTag().toString()));
Util.startActivity(this, ActivityWebview.class, b, false);
break;
case R.id.tv_notice:
b.putString("title", getText(tv_notice));
b.putString("url", String.format(SJECHttpHandler.URL_PAGE_ARTICLE_CONTENT, tv_notice.getTag().toString()));
Util.startActivity(this, ActivityWebview.class, b, false);
break;
case R.id.tv_login:
if (GlobalData.curUser == null) {
Util.startActivity(MainActivity.this, ActivityLogin.class, true);
} else {
Editor editor = PrefUtil.getEditor(this);
editor.clear();
editor.commit();
GlobalData.curUser = null;
tv_login.setText("登录");
Util.createToast(MainActivity.this, R.string.msg_dialog_cancel_success, 3000).show();
}
break;
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(receiver);
}
/*
* 查询版本更新相关
*/
public static boolean IS_NEED_UPDATE = false;
public static String URL_NEW_VERSION = "";
public static String UPDATE_CONTENT = "";
DownloadManager downloadmanager = null;
public void checkUpdateApk(Context context) {
new SJECHttpHandler(cb, context).checkVersion();
}
AsyncHttpCallBack cb = new AsyncHttpCallBack() {
@Override
public void onSuccess(String response) {
super.onSuccess(response);
LogUtil.d("%s", response);
JSONObject obj;
try {
obj = new JSONObject(response);
if (obj.optString("result").equals("true")) {
JSONObject json = obj.getJSONObject("data");
int versionCode = json.optInt("VersionCode", 0);
IS_NEED_UPDATE = AppData.VERSION_CODE < versionCode ? true : false;
URL_NEW_VERSION = SJECHttpHandler.BASE_URL + json.optString("DownloadUrl");
UPDATE_CONTENT = json.optString("UpdateContent", "");
if (IS_NEED_UPDATE) {
showUpdateApkDialog(MainActivity.this, Constant.DOWNLOAD_APK_NAME, URL_NEW_VERSION,
UPDATE_CONTENT);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(String message) {
super.onFailure(message);
LogUtil.d("%s", message);
}
};
AsyncHttpCallBack cbGetCommonData = new AsyncHttpCallBack() {
@Override
public void onSuccess(String response) {
super.onSuccess(response);
LogUtil.d("%s", response);
JSONObject obj;
try {
obj = new JSONObject(response);
if (obj.optString("result").equals("true")) {
Gson gson = new Gson();
GlobalData.listCommonData = gson.fromJson(obj.getString("data"),
new TypeToken<ArrayList<EntityCommonData>>() {
}.getType());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(String message) {
super.onFailure(message);
LogUtil.d("%s", message);
}
};
AsyncHttpCallBack cbGetModule = new AsyncHttpCallBack() {
@Override
public void onSuccess(String response) {
super.onSuccess(response);
LogUtil.d("%s", response);
JSONObject obj;
try {
obj = new JSONObject(response);
if (obj.optString("result").equals("true")) {
Gson gson = new Gson();
GlobalData.listModule = gson.fromJson(obj.getString("data"),
new TypeToken<ArrayList<EntityModule>>() {
}.getType());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(String message) {
super.onFailure(message);
LogUtil.d("%s", message);
}
};
AsyncHttpCallBack cbLocation = new AsyncHttpCallBack() {
@Override
public void onSuccess(String response) {
super.onSuccess(response);
LogUtil.d("%s", response);
JSONObject obj;
try {
obj = new JSONObject(response);
if (obj.optString("result").equals("true")) {
Gson gson = new Gson();
ArrayList<EntityLocation> list = gson.fromJson(obj.getString("data"),
new TypeToken<ArrayList<EntityLocation>>() {
}.getType());
GlobalData.listProvince.clear();
GlobalData.listCity.clear();
GlobalData.listCounty.clear();
GlobalData.listProvince.add(new EntityLocation(-1, "--请选择省份--", "", "", -9999, 2));
GlobalData.listCity.add(new EntityLocation(-1, "--请选择城市--", "", "", -9999, 3));
GlobalData.listCounty.add(new EntityLocation(-1, "--请选择区/县--", "", "", -9999, 4));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).LocationLevel == 2) {
GlobalData.listProvince.add(list.get(i));
} else if (list.get(i).LocationLevel == 3) {
GlobalData.listCity.add(list.get(i));
} else if (list.get(i).LocationLevel == 4) {
GlobalData.listCounty.add(list.get(i));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(String message) {
super.onFailure(message);
LogUtil.d("%s", message);
}
};
AsyncHttpCallBack cbButchery = new AsyncHttpCallBack() {
@Override
public void onSuccess(String response) {
super.onSuccess(response);
LogUtil.d("%s", response);
JSONObject obj;
try {
obj = new JSONObject(response);
if (obj.optString("result").equals("true")) {
Gson gson = new Gson();
GlobalData.listButchery = gson.fromJson(obj.getString("data"),
new TypeToken<ArrayList<EntityButchery>>() {
}.getType());
GlobalData.listButchery.add(0, new EntityButchery("", "--请选择--", "", "", "", ""));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(String message) {
super.onFailure(message);
LogUtil.d("%s", message);
}
};
public void showUpdateApkDialog(final Context context, final String savePath, final String url_download,
final String update_content) {
StringBuffer sb = new StringBuffer();
sb.append("更新内容:\n" + update_content);
Dialog dialog = new AlertDialog.Builder(context).setTitle(R.string.welcome_dialog_version_msg)
.setMessage(sb.toString())
.setPositiveButton(R.string.welcome_dialog_version_confirm, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
startDownloadApk(context, savePath, url_download);
}
}).setNegativeButton(R.string.welcome_dialog_version_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}).create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
// }
}
public long startDownloadApk(Context context, String savePath, String url_download) {
if (new File(savePath).exists()) {
new File(savePath).delete();
}
downloadmanager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
Request req = new DownloadManager.Request(Uri.parse(url_download));
req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
req.setAllowedOverRoaming(false);
req.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
req.setDestinationUri(Uri.fromFile(new File(savePath)));
long tmp = downloadmanager.enqueue(req);
return tmp;
}
/**
* 监听是否下载apk成功,这个方法放在receiver中用来监听 android.intent.action.DOWNLOAD_COMPLETE
* android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED
*
* @param downloadmanager
* @param downloadID
* @param context
* @param apkPath
*/
public void validDownloadStatus(long downloadID) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadID);
Cursor c = downloadmanager.query(query);
int status = -1;
if (c != null && c.moveToFirst()) {
status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
}
c.close();
if (status == 8) {
LogUtil.d("%s", "下载成功");
// 下载成功,调用系统的安装程序
updateAndInstall();
}
}
/**
* 安装/覆盖软件
*
* @param context
* @param apkPath
*/
public void updateAndInstall() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(new File(Constant.DOWNLOAD_APK_NAME)),
"application/vnd.android.package-archive");
startActivity(intent);
}
AsyncHttpCallBack cbGetButchery = new AsyncHttpCallBack() {
@Override
public void onSuccess(String response) {
super.onSuccess(response);
LogUtil.d("%s", response);
JSONObject obj;
try {
obj = new JSONObject(response);
if (obj.optString("result").equals("true")) {
Gson gson = new Gson();
GlobalData.listButcheryByUser = gson.fromJson(obj.getString("data"),
new TypeToken<ArrayList<EntityButchery>>() {
}.getType());
} else {
Util.createToast(MainActivity.this,
obj.optString("desc", getString(R.string.msg_failed_getButcheryGroup)), 3000).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(String message) {
super.onFailure(message);
LogUtil.d("%s", message);
}
};
}
|
package random;
import java.util.concurrent.CountDownLatch;
import static random.StaticBlockAndLineExecution3.latch;
/*
"Static initializers are run by the JVM at class initialization time, after class loading
but before the class is used by any thread. Because the JVM acquires a lock during initialization [JLS 12.4.2] and
this lock is acquired by each thread at least once to ensure that the class has been loaded,
memory writes made during static initialization are automatically visible to all threads."(Goetz 16.2.3)
*/
public class StaticBlockAndLineExecution3 {
static CountDownLatch latch = new CountDownLatch(1);
static Thread mainThread = Thread.currentThread();
public static void main(String[] args) throws InterruptedException {
new Thread(() -> keepLooping()).start();
new Thread(() -> keepLooping()).start();
int x = AllThreadsStopper.threadStopper;
}
static void keepLooping() {
while (true) {
try {
latch.await();
/*@ mark*/ System.out.println("This will never print " + AllThreadsStopper.threadStopper);
// however, if you add the three lines below, the haltAllThreadsAndNeverReturn would throw an Exception and return
/*"A method returns to the code that invoked it when it completes
all the statements in the method, reaches a return statement, or throws an exception (covered later), whichever occurs first."
- https://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html */
// this will end up leaving threadStopper as is, where the default value was 0 to start with so it will print zero
// of course you would need to comment out the line above that is marked with /*@ mark*/
// mainThread.interrupt();
// Thread.sleep(500);
// System.out.println("This will print " + AllThreadsStopper.threadStopper);
} catch (InterruptedException e) {}
System.out.println("This is thread " + Thread.currentThread().getName());
}
}
}
class AllThreadsStopper {
static int threadStopper;
static {
try {
threadStopper = haltAllThreadsAndNeverReturn();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static int haltAllThreadsAndNeverReturn() throws InterruptedException {
System.out.println("haltAllThreadsAndNeverReturn called but only once from main since its locked from " + Thread.currentThread().getName());
latch.countDown();
new CountDownLatch(1).await();
return 10000;
}
}
|
package com.xujiangjun.archetype.manager.consumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* 封装第三方服务接口(参考此命名方式)
*
* @author xujiangjun
* @since 2018.05.20
*/
@Slf4j
@Service
public class LocalShopService {
}
|
package org.study.core.concurrency.thread;
import java.util.concurrent.locks.Lock;
/**
* Created by iovchynnikov on 7/29/2015.
*/
public class Deadlocks {
public void run() {
Thread thread1 = new Deadlocks.DeadlockThread();
}
private class DeadlockThread extends Thread {
@Override
public void run() {
}
}
}
|
package nl.themelvin.questlib.listeners;
import nl.themelvin.questlib.QuestLib;
import nl.themelvin.questlib.abstracts.Quest;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerQuitEvent;
public class QuitListener extends Listener<PlayerQuitEvent> {
@EventHandler
public void listen(PlayerQuitEvent event) {
Player player = event.getPlayer();
QuestLib questLib = QuestLib.getInstance();
if(questLib.hasQuest(player)) {
Quest quest = questLib.getQuest(player);
quest.pause();
}
}
}
|
package VSMWordEmbeddingsNew;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.logging.Logger;
import no.uib.cipr.matrix.DenseVector;
import no.uib.cipr.matrix.Vector;
import no.uib.cipr.matrix.VectorEntry;
import VSMConstants.VSMContant;
import VSMLogger.VSMLogger;
import VSMWordEmbeddingsNew.EmbeddedVectorBean;
import VSMUtilityClasses.VSMUtil;
/**
* The class to generate the sentence vectors from the embedded feature vectors
*
* @author s1444025
*
*/
public class WordEmbeddingsFull {
private static Logger LOGGER;
private static File[] topLevelWordFolders;
private static Vector wordEmbedding;
// private static int nonTerminals;
private static Vector[] embeddedFeatureVectors;
private static File[] embeddedChunkVectors;
private static File[] chunks;
private static WordEmbeddingBean vecBean;
private static HashMap<String, DenseVector> embeddingsMap;
private static Vector ccinSyn;
private static Vector ccoutSyn;
private static Vector ccinSem;
private static Vector ccoutSem;
private static Vector nninSyn;
private static Vector nnoutSyn;
private static Vector nninSem;
private static Vector nnoutSem;
private static Vector ininSyn;
private static Vector inoutSyn;
private static Vector ininSem;
private static Vector inoutSem;
private static Vector jjinSyn;
private static Vector jjoutSyn;
private static Vector jjinSem;
private static Vector jjoutSem;
private static Vector nnpinSyn;
private static Vector nnpoutSyn;
private static Vector nnpinSem;
private static Vector nnpoutSem;
private static Vector nnsinSyn;
private static Vector nnsoutSyn;
private static Vector nnsinSem;
private static Vector nnsoutSem;
private static Vector prpinSyn;
private static Vector prpoutSyn;
private static Vector prpinSem;
private static Vector prpoutSem;
private static Vector vbpinSyn;
private static Vector vbpoutSyn;
private static Vector vbpinSem;
private static Vector vbpoutSem;
private static Vector vbninSyn;
private static Vector vbnoutSyn;
private static Vector vbninSem;
private static Vector vbnoutSem;
private static Vector vbginSyn;
private static Vector vbgoutSyn;
private static Vector vbginSem;
private static Vector vbgoutSem;
private static Vector rbinSyn;
private static Vector rboutSyn;
private static Vector rbinSem;
private static Vector rboutSem;
private static Vector dtinSyn;
private static Vector dtoutSyn;
private static Vector dtinSem;
private static Vector dtoutSem;
private static DenseVector vbdinSyn;
private static DenseVector vbdoutSyn;
private static DenseVector vbdinSem;
private static DenseVector vbdoutSem;
private static File[] wordDirectories;
private static String folderName;
static {
embeddingsMap = new LinkedHashMap<>();
}
public static void main(String[] args) {
folderName = getFolderName(args);
LOGGER = VSMLogger.setup(WordEmbeddingsFull.class.getName() + "_"
+ folderName);
System.out.println("++FOLDER NAME++" + folderName);
topLevelWordFolders = getTopLevelWordFolders(VSMContant.WORD_VECS_EMBEDDED_CHUNKS);
System.out.println("New!!!");
sortByNumber(topLevelWordFolders);
// formDirectoryStructure();
for (File topLevelFolder : topLevelWordFolders) {
if (topLevelFolder.getName().equalsIgnoreCase(folderName)) {
getWordDirectories(topLevelFolder);
for (File wordDirectory : wordDirectories) {
wordEmbedding = new DenseVector(24000);
embeddedFeatureVectors = new DenseVector[52];
setup();
chunks = VSMUtil.getWordChunks(wordDirectory, LOGGER);
for (File chunk : chunks) {
embeddedChunkVectors = VSMUtil.getEmbeddedChunkVecs(
chunk, LOGGER);
System.out.println("++++Number of Vectors+++ "
+ embeddedChunkVectors.length);
String chunkName = chunk.getName();
if (embeddedChunkVectors != null) {
switch (chunkName) {
case "CC":
embedCC();
break;
case "NN":
embedNN();
break;
case "IN":
embedIN();
break;
case "JJ":
embedJJ();
break;
case "NNP":
embedNNP();
break;
case "NNS":
embedNNS();
break;
case "PRP":
embedPRP();
break;
case "RB":
embedRB();
break;
case "VBG":
embedVBG();
break;
case "VBP":
embedVBP();
break;
case "VBN":
embedVBN();
break;
default:
break;
}
}
}
formWordEmbedding(wordDirectory);
serializeWordEmbedding(wordDirectory);
}
}
}
serializeEmbeddingsMap();
}
private static int checkWordEmbeddedFolder(File wordDirectory) {
File file = new File(wordDirectory.getParent() + "_embed");
if (file.exists()) {
String filename = file.getAbsolutePath() + "/"
+ wordDirectory.getName() + "/embedding.ser";
File wordVecFile = new File(filename);
if (wordVecFile.exists()) {
System.out
.println("+++++Word Embedding Already Exists hence returning and not forming the vectors");
return -1;
}
}
return 0;
}
private static String getFolderName(String... args) {
if (args.length > 0) {
return args[0];
} else {
System.out.println("PLEASE GIVE A FLOLDER NAME");
System.exit(-1);
}
return null;
}
private static void serializeEmbeddingsMap() {
ObjectOutput embeddings = null;
try {
embeddings = new ObjectOutputStream(new FileOutputStream(
"/group/project/vsm-nfs/WordEmbeddings1/WordEmbeddings/wordEmbeddings"
+ folderName + ".ser", false));
embeddings.writeObject(embeddingsMap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (embeddings != null) {
embeddings.flush();
embeddings.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void getWordDirectories(File topLevelFolder) {
wordDirectories = topLevelFolder.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return !pathname.isHidden();
}
});
}
private static File[] getTopLevelWordFolders(String wordVecsEmbeddedChunks) {
File[] topLevelFolders = new File(wordVecsEmbeddedChunks)
.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return !pathname.isHidden();
}
});
return topLevelFolders;
}
private static void serializeWordEmbedding(File wordDirectory) {
vecBean = new WordEmbeddingBean();
vecBean.setWordEmbedding((DenseVector) wordEmbedding);
System.out.println("+++INSERTING THE WORD IN THE MAP++"
+ wordDirectory.getName());
embeddingsMap.put(wordDirectory.getName(), (DenseVector) wordEmbedding);
// serializeWordVector(vecBean, wordDirectory);
}
private static void formWordEmbedding(File wordDirectory) {
int i = 0;
for (Vector vec : embeddedFeatureVectors) {
i = i + vec.size();
}
System.out.println(i);
int startIdx = 0;
Iterator<VectorEntry> iterator = null;
for (Vector vector : embeddedFeatureVectors) {
iterator = vector.iterator();
while (iterator.hasNext()) {
VectorEntry e = iterator.next();
int idx = e.index() + startIdx;
double val = e.get();
wordEmbedding.add(idx, val);
}
startIdx = startIdx + vector.size();
}
}
private static void embedVBN() {
int count = 0;
for (File embeddeVec : embeddedChunkVectors) {
count++;
EmbeddedVectorBean vectorBean = readFeatureVectorBeanEmbedded(embeddeVec
.getAbsolutePath());
if (vectorBean != null) {
if (vectorBean.getPhiEmbedded() != null)
vbninSyn = vbninSyn.add(vectorBean.getPhiEmbedded());
if (vectorBean.getPsiEmbedded() != null)
vbnoutSyn = vbnoutSyn.add(vectorBean.getPsiEmbedded());
if (vectorBean.getPhiSem() != null)
vbninSem = vbninSem.add(vectorBean.getPhiSem());
if (vectorBean.getPsiSem() != null)
vbnoutSem = vbnoutSem.add(vectorBean.getPsiSem());
} else {
LOGGER.severe("++++VECTOR BEAN NULL FOR: "
+ embeddeVec.getAbsolutePath());
}
}
vbninSyn = vbninSyn.scale((double) 1 / count);
vbnoutSyn = vbnoutSyn.scale((double) 1 / count);
vbninSem = vbninSem.scale((double) 1 / count);
vbnoutSem = vbnoutSem.scale((double) 1 / count);
}
private static void embedVBP() {
int count = 0;
for (File embeddeVec : embeddedChunkVectors) {
count++;
EmbeddedVectorBean vectorBean = readFeatureVectorBeanEmbedded(embeddeVec
.getAbsolutePath());
if (vectorBean != null) {
if (vectorBean.getPhiEmbedded() != null)
vbpinSyn = vbpinSyn.add(vectorBean.getPhiEmbedded());
if (vectorBean.getPsiEmbedded() != null)
vbpoutSyn = vbpoutSyn.add(vectorBean.getPsiEmbedded());
if (vectorBean.getPhiSem() != null)
vbpinSem = vbpinSem.add(vectorBean.getPhiSem());
if (vectorBean.getPsiSem() != null)
vbpoutSem = vbpoutSem.add(vectorBean.getPsiSem());
} else {
LOGGER.severe("++++VECTOR BEAN NULL FOR: "
+ embeddeVec.getAbsolutePath());
}
}
vbpinSyn = vbpinSyn.scale((double) 1 / count);
vbpoutSyn = vbpoutSyn.scale((double) 1 / count);
vbpinSem = vbpinSem.scale((double) 1 / count);
vbpoutSem = vbpoutSem.scale((double) 1 / count);
}
private static void embedVBG() {
int count = 0;
for (File embeddeVec : embeddedChunkVectors) {
count++;
EmbeddedVectorBean vectorBean = readFeatureVectorBeanEmbedded(embeddeVec
.getAbsolutePath());
if (vectorBean != null) {
if (vectorBean.getPhiEmbedded() != null)
vbginSyn = vbginSyn.add(vectorBean.getPhiEmbedded());
if (vectorBean.getPsiEmbedded() != null)
vbgoutSyn = vbgoutSyn.add(vectorBean.getPsiEmbedded());
if (vectorBean.getPhiSem() != null)
vbginSem = vbginSem.add(vectorBean.getPhiSem());
if (vectorBean.getPsiSem() != null)
vbgoutSem = vbgoutSem.add(vectorBean.getPsiSem());
} else {
LOGGER.severe("++++VECTOR BEAN NULL FOR: "
+ embeddeVec.getAbsolutePath());
}
}
vbginSyn = vbginSyn.scale((double) 1 / count);
vbgoutSyn = vbgoutSyn.scale((double) 1 / count);
vbginSem = vbginSem.scale((double) 1 / count);
vbgoutSem = vbgoutSem.scale((double) 1 / count);
}
private static void embedRB() {
int count = 0;
for (File embeddeVec : embeddedChunkVectors) {
count++;
EmbeddedVectorBean vectorBean = readFeatureVectorBeanEmbedded(embeddeVec
.getAbsolutePath());
if (vectorBean != null) {
if (vectorBean.getPhiEmbedded() != null)
rbinSyn = rbinSyn.add(vectorBean.getPhiEmbedded());
if (vectorBean.getPsiEmbedded() != null)
rboutSyn = rboutSyn.add(vectorBean.getPsiEmbedded());
if (vectorBean.getPhiSem() != null)
rbinSem = rbinSem.add(vectorBean.getPhiSem());
if (vectorBean.getPsiSem() != null)
rboutSem = rboutSem.add(vectorBean.getPsiSem());
} else {
LOGGER.severe("++++VECTOR BEAN NULL FOR: "
+ embeddeVec.getAbsolutePath());
}
}
rbinSyn = rbinSyn.scale((double) 1 / count);
rboutSyn = rboutSyn.scale((double) 1 / count);
rbinSem = rbinSem.scale((double) 1 / count);
rboutSem = rboutSem.scale((double) 1 / count);
}
private static void embedPRP() {
int count = 0;
for (File embeddeVec : embeddedChunkVectors) {
count++;
EmbeddedVectorBean vectorBean = readFeatureVectorBeanEmbedded(embeddeVec
.getAbsolutePath());
if (vectorBean != null) {
if (vectorBean.getPhiEmbedded() != null)
prpinSyn = prpinSyn.add(vectorBean.getPhiEmbedded());
if (vectorBean.getPsiEmbedded() != null)
prpoutSyn = prpoutSyn.add(vectorBean.getPsiEmbedded());
if (vectorBean.getPhiSem() != null)
prpinSem = prpinSem.add(vectorBean.getPhiSem());
if (vectorBean.getPsiSem() != null)
prpoutSem = prpoutSem.add(vectorBean.getPsiSem());
} else {
LOGGER.severe("++++VECTOR BEAN NULL FOR: "
+ embeddeVec.getAbsolutePath());
}
}
prpinSyn = prpinSyn.scale((double) 1 / count);
prpoutSyn = prpoutSyn.scale((double) 1 / count);
prpinSem = prpinSem.scale((double) 1 / count);
prpoutSem = prpoutSem.scale((double) 1 / count);
}
private static void embedNNS() {
int count = 0;
for (File embeddeVec : embeddedChunkVectors) {
count++;
EmbeddedVectorBean vectorBean = readFeatureVectorBeanEmbedded(embeddeVec
.getAbsolutePath());
if (vectorBean != null) {
if (vectorBean.getPhiEmbedded() != null)
nnsinSyn = nnsinSyn.add(vectorBean.getPhiEmbedded());
if (vectorBean.getPsiEmbedded() != null)
nnsoutSyn = nnsoutSyn.add(vectorBean.getPsiEmbedded());
if (vectorBean.getPhiSem() != null)
nnsinSem = nnsinSem.add(vectorBean.getPhiSem());
if (vectorBean.getPsiSem() != null)
nnsoutSem = nnsoutSem.add(vectorBean.getPsiSem());
} else {
LOGGER.severe("++++VECTOR BEAN NULL FOR: "
+ embeddeVec.getAbsolutePath());
}
}
nnsinSyn = nnsinSyn.scale((double) 1 / count);
nnsoutSyn = nnsoutSyn.scale((double) 1 / count);
nnsinSem = nnsinSem.scale((double) 1 / count);
nnsoutSem = nnsoutSem.scale((double) 1 / count);
}
private static void embedNNP() {
int count = 0;
for (File embeddeVec : embeddedChunkVectors) {
count++;
EmbeddedVectorBean vectorBean = readFeatureVectorBeanEmbedded(embeddeVec
.getAbsolutePath());
if (vectorBean != null) {
if (vectorBean.getPhiEmbedded() != null)
nnpinSyn = nnpinSyn.add(vectorBean.getPhiEmbedded());
if (vectorBean.getPsiEmbedded() != null)
nnpoutSyn = nnpoutSyn.add(vectorBean.getPsiEmbedded());
if (vectorBean.getPhiSem() != null)
nnpinSem = nnpinSem.add(vectorBean.getPhiSem());
if (vectorBean.getPsiSem() != null)
nnpoutSem = nnpoutSem.add(vectorBean.getPsiSem());
} else {
LOGGER.severe("++++VECTOR BEAN NULL FOR: "
+ embeddeVec.getAbsolutePath());
}
}
nnpinSyn = nnpinSyn.scale((double) 1 / count);
nnpoutSyn = nnpoutSyn.scale((double) 1 / count);
nnpinSem = nnpinSem.scale((double) 1 / count);
nnpoutSem = nnpoutSem.scale((double) 1 / count);
}
private static void embedJJ() {
int count = 0;
for (File embeddeVec : embeddedChunkVectors) {
count++;
EmbeddedVectorBean vectorBean = readFeatureVectorBeanEmbedded(embeddeVec
.getAbsolutePath());
if (vectorBean != null) {
if (vectorBean.getPhiEmbedded() != null)
jjinSyn = jjinSyn.add(vectorBean.getPhiEmbedded());
if (vectorBean.getPsiEmbedded() != null)
jjoutSyn = jjoutSyn.add(vectorBean.getPsiEmbedded());
if (vectorBean.getPhiSem() != null)
jjinSem = jjinSem.add(vectorBean.getPhiSem());
if (vectorBean.getPsiSem() != null)
jjoutSem = jjoutSem.add(vectorBean.getPsiSem());
} else {
LOGGER.severe("++++VECTOR BEAN NULL FOR: "
+ embeddeVec.getAbsolutePath());
}
}
jjinSyn = jjinSyn.scale((double) 1 / count);
jjoutSyn = jjoutSyn.scale((double) 1 / count);
jjinSem = jjinSem.scale((double) 1 / count);
jjoutSem = jjoutSem.scale((double) 1 / count);
}
private static void embedIN() {
int count = 0;
for (File embeddeVec : embeddedChunkVectors) {
count++;
EmbeddedVectorBean vectorBean = readFeatureVectorBeanEmbedded(embeddeVec
.getAbsolutePath());
if (vectorBean != null) {
if (vectorBean.getPhiEmbedded() != null)
ininSyn = ininSyn.add(vectorBean.getPhiEmbedded());
if (vectorBean.getPsiEmbedded() != null)
inoutSyn = inoutSyn.add(vectorBean.getPsiEmbedded());
if (vectorBean.getPhiSem() != null)
ininSem = ininSem.add(vectorBean.getPhiSem());
if (vectorBean.getPsiSem() != null)
inoutSem = inoutSem.add(vectorBean.getPsiSem());
} else {
LOGGER.severe("++++VECTOR BEAN NULL FOR: "
+ embeddeVec.getAbsolutePath());
}
}
ininSyn = ininSyn.scale((double) 1 / count);
inoutSyn = inoutSyn.scale((double) 1 / count);
ininSem = ininSem.scale((double) 1 / count);
inoutSem = inoutSem.scale((double) 1 / count);
}
private static void embedNN() {
int count = 0;
for (File embeddeVec : embeddedChunkVectors) {
count++;
EmbeddedVectorBean vectorBean = readFeatureVectorBeanEmbedded(embeddeVec
.getAbsolutePath());
if (vectorBean != null) {
if (vectorBean.getPhiEmbedded() != null)
nninSyn = nninSyn.add(vectorBean.getPhiEmbedded());
if (vectorBean.getPsiEmbedded() != null)
nnoutSyn = nnoutSyn.add(vectorBean.getPsiEmbedded());
if (vectorBean.getPhiSem() != null)
nninSem = nninSem.add(vectorBean.getPhiSem());
if (vectorBean.getPsiSem() != null)
nnoutSem = nnoutSem.add(vectorBean.getPsiSem());
} else {
LOGGER.severe("++++VECTOR BEAN NULL FOR: "
+ embeddeVec.getAbsolutePath());
}
}
nninSyn = nninSyn.scale((double) 1 / count);
nnoutSyn = nnoutSyn.scale((double) 1 / count);
nninSem = nninSem.scale((double) 1 / count);
nnoutSem = nnoutSem.scale((double) 1 / count);
}
private static void embedCC() {
int count = 0;
for (File embeddeVec : embeddedChunkVectors) {
count++;
EmbeddedVectorBean vectorBean = readFeatureVectorBeanEmbedded(embeddeVec
.getAbsolutePath());
if (vectorBean != null) {
if (vectorBean.getPhiEmbedded() != null)
ccinSyn = ccinSyn.add(vectorBean.getPhiEmbedded());
if (vectorBean.getPsiEmbedded() != null)
ccoutSyn = ccoutSyn.add(vectorBean.getPsiEmbedded());
if (vectorBean.getPhiSem() != null)
ccinSem = ccinSem.add(vectorBean.getPhiSem());
if (vectorBean.getPsiSem() != null)
ccoutSem = ccoutSem.add(vectorBean.getPsiSem());
} else {
LOGGER.severe("++++VECTOR BEAN NULL FOR: "
+ embeddeVec.getAbsolutePath());
}
}
ccinSyn = ccinSyn.scale((double) 1 / count);
ccoutSyn = ccoutSyn.scale((double) 1 / count);
ccinSem = ccinSem.scale((double) 1 / count);
ccoutSem = ccoutSem.scale((double) 1 / count);
}
private static void setup() {
ccinSyn = new DenseVector(30);
ccoutSyn = new DenseVector(30);
ccinSem = new DenseVector(14);
ccoutSem = new DenseVector(14);
nninSyn = new DenseVector(640);
nnoutSyn = new DenseVector(640);
nninSem = new DenseVector(640);
nnoutSem = new DenseVector(640);
ininSyn = new DenseVector(96);
inoutSyn = new DenseVector(96);
ininSem = new DenseVector(37);
inoutSem = new DenseVector(37);
jjinSyn = new DenseVector(640);
jjoutSyn = new DenseVector(640);
jjinSem = new DenseVector(100);
jjoutSem = new DenseVector(100);
nnpinSyn = new DenseVector(640);
nnpoutSyn = new DenseVector(640);
nnpinSem = new DenseVector(640);
nnpoutSem = new DenseVector(640);
nnsinSyn = new DenseVector(640);
nnsoutSyn = new DenseVector(640);
nnsinSem = new DenseVector(640);
nnsoutSem = new DenseVector(640);
prpinSyn = new DenseVector(42);
prpoutSyn = new DenseVector(42);
prpinSem = new DenseVector(13);
prpoutSem = new DenseVector(13);
vbpinSyn = new DenseVector(640);
vbpoutSyn = new DenseVector(640);
vbpinSem = new DenseVector(640);
vbpoutSem = new DenseVector(640);
vbninSyn = new DenseVector(640);
vbnoutSyn = new DenseVector(640);
vbninSem = new DenseVector(640);
vbnoutSem = new DenseVector(640);
vbginSyn = new DenseVector(640);
vbgoutSyn = new DenseVector(640);
vbginSem = new DenseVector(640);
vbgoutSem = new DenseVector(640);
rbinSyn = new DenseVector(640);
rboutSyn = new DenseVector(640);
rbinSem = new DenseVector(640);
rboutSem = new DenseVector(640);
dtinSyn = new DenseVector(10);
dtoutSyn = new DenseVector(10);
dtinSem = new DenseVector(4);
dtoutSem = new DenseVector(4);
vbdinSyn = new DenseVector(640);
vbdoutSyn = new DenseVector(640);
vbdinSem = new DenseVector(640);
vbdoutSem = new DenseVector(640);
embeddedFeatureVectors[0] = ininSyn;
embeddedFeatureVectors[1] = inoutSyn;
embeddedFeatureVectors[2] = ininSem;
embeddedFeatureVectors[3] = inoutSem;
embeddedFeatureVectors[4] = nninSyn;
embeddedFeatureVectors[5] = nnoutSyn;
embeddedFeatureVectors[6] = nninSem;
embeddedFeatureVectors[7] = nnoutSem;
embeddedFeatureVectors[8] = ccinSyn;
embeddedFeatureVectors[9] = ccoutSyn;
embeddedFeatureVectors[10] = ccinSem;
embeddedFeatureVectors[11] = ccoutSem;
embeddedFeatureVectors[12] = jjinSyn;
embeddedFeatureVectors[13] = jjoutSyn;
embeddedFeatureVectors[14] = jjinSem;
embeddedFeatureVectors[15] = jjoutSem;
embeddedFeatureVectors[16] = nnpinSyn;
embeddedFeatureVectors[17] = nnpoutSyn;
embeddedFeatureVectors[18] = nnpinSem;
embeddedFeatureVectors[19] = nnpoutSem;
embeddedFeatureVectors[20] = nnsinSyn;
embeddedFeatureVectors[21] = nnsoutSyn;
embeddedFeatureVectors[22] = nnsinSem;
embeddedFeatureVectors[23] = nnsoutSem;
embeddedFeatureVectors[24] = prpinSyn;
embeddedFeatureVectors[25] = prpoutSyn;
embeddedFeatureVectors[26] = prpinSem;
embeddedFeatureVectors[27] = prpoutSem;
embeddedFeatureVectors[28] = vbpinSyn;
embeddedFeatureVectors[29] = vbpoutSyn;
embeddedFeatureVectors[30] = vbpinSem;
embeddedFeatureVectors[31] = vbpoutSem;
embeddedFeatureVectors[32] = rbinSyn;
embeddedFeatureVectors[33] = rboutSyn;
embeddedFeatureVectors[34] = rbinSem;
embeddedFeatureVectors[35] = rboutSem;
embeddedFeatureVectors[36] = vbginSyn;
embeddedFeatureVectors[37] = vbgoutSyn;
embeddedFeatureVectors[38] = vbginSem;
embeddedFeatureVectors[39] = vbgoutSem;
embeddedFeatureVectors[40] = vbninSyn;
embeddedFeatureVectors[41] = vbnoutSyn;
embeddedFeatureVectors[42] = vbninSem;
embeddedFeatureVectors[43] = vbnoutSem;
embeddedFeatureVectors[44] = dtinSyn;
embeddedFeatureVectors[45] = dtoutSyn;
embeddedFeatureVectors[46] = dtinSem;
embeddedFeatureVectors[47] = dtoutSem;
embeddedFeatureVectors[48] = vbdinSyn;
embeddedFeatureVectors[49] = vbdoutSyn;
embeddedFeatureVectors[50] = vbdinSem;
embeddedFeatureVectors[51] = vbdoutSem;
}
public static void serializeWordVector(WordEmbeddingBean vecBean,
File wordDirectory) {
File file = new File("/group/project/vsm-nfs/WordFeatureVecsEmbedded1/"
+ folderName + "_embed");
if (!file.exists()) {
file.mkdir();
}
String filename = file.getAbsolutePath() + "/"
+ wordDirectory.getName() + "/embedding.ser";
File wordVecFile = new File(filename);
if (wordVecFile.exists()) {
System.out.println("+++++Word Embedding Already Exists");
return;
} else {
try {
wordVecFile.getParentFile().mkdir();
wordVecFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename, false);
out = new ObjectOutputStream(fos);
out.writeObject(vecBean);
System.out.println("**serialized at** " + filename);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
out.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static EmbeddedVectorBean readFeatureVectorBeanEmbedded(
String fileName) {
EmbeddedVectorBean vectorBean = null;
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(fileName);
in = new ObjectInputStream(fis);
vectorBean = (EmbeddedVectorBean) in.readObject();
} catch (IOException ex) {
LOGGER.severe("IO excpetion while reading++++ " + fileName);
ex.printStackTrace();
} catch (ClassNotFoundException cnfe) {
LOGGER.severe("FNE excpeiton while reading++++ " + fileName);
cnfe.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
else
LOGGER.severe("FIS NULL+++ for +++ " + fileName);
if (in != null)
in.close();
} catch (IOException e) {
LOGGER.severe("+++EXCEPTION WHILE CLOSING THE FILE" + fileName);
e.printStackTrace();
}
}
return vectorBean;
}
public static void sortByNumber(File[] files) {
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
int n1 = extractNumer(o1.getName());
int n2 = extractNumer(o2.getName());
return n1 - n2;
}
private int extractNumer(String name) {
int i = 0;
try {
int s = name.indexOf('_') + 1;
int e = name.lastIndexOf('.');
String number = name.substring(s, e);
i = Integer.parseInt(number);
} catch (Exception e) {
i = 0;
}
return i;
}
});
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* MvQuality generated by hbm2java
*/
public class MvQuality implements java.io.Serializable {
private MvQualityId id;
public MvQuality() {
}
public MvQuality(MvQualityId id) {
this.id = id;
}
public MvQualityId getId() {
return this.id;
}
public void setId(MvQualityId id) {
this.id = id;
}
}
|
package club.dao.mysql.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
private static final String dbUrl = "jdbc:mysql://localhost:3306/club";
private static final String dbUserName = "root";
private static final String dbPassword = "password";
private static final String dbDriver = "com.mysql.jdbc.Driver";
public static Connection getConnection() throws SQLException, ClassNotFoundException {
Class.forName(dbDriver);
Connection conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
return conn;
}
}
|
package com.santhosh.model;
import java.sql.Timestamp;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Table(name="crosstransaction")
public class Cstatus {
@Id
private int sno;
@NotNull(message="Customer ID cannot be empty")
private String custid;
@NotNull(message="Source Account cannot be empty")
private String sourceaccount;
@NotNull(message="Target Account cannot be empty")
private String targetaccount;
@NotNull(message="Amount Name cannot be empty")
private String amountname;
@NotNull(message="Amount cannot be empty")
private String amount;
private String amountinr;
private String transactionnumber;
private Timestamp timestamp;
public int getSno() {
return sno;
}
public void setSno(int sno) {
this.sno = sno;
}
public String getCustid() {
return custid;
}
public void setCustid(String custid) {
this.custid = custid;
}
public String getSourceaccount() {
return sourceaccount;
}
public void setSourceaccount(String sourceaccount) {
this.sourceaccount = sourceaccount;
}
public String getTargetaccount() {
return targetaccount;
}
public void setTargetaccount(String targetaccount) {
this.targetaccount = targetaccount;
}
public String getAmountname() {
return amountname;
}
public void setAmountname(String amountname) {
this.amountname = amountname;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getAmountinr() {
return amountinr;
}
public void setAmountinr(String amountinr) {
this.amountinr = amountinr;
}
public String getTransactionnumber() {
return transactionnumber;
}
public void setTransactionnumber(String transactionnumber) {
this.transactionnumber = transactionnumber;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
@Override
public String toString() {
return "Cstatus [sno=" + sno + ", custid=" + custid + ", sourceaccount=" + sourceaccount + ", targetaccount="
+ targetaccount + ", amountname=" + amountname + ", amount=" + amount + ", amountinr=" + amountinr
+ ", transactionnumber=" + transactionnumber + ", timestamp=" + timestamp + "]";
}
}
|
/** (Display current date and time) Listing 2.7, ShowCurrentTime.java, displays the current time.
* Improve this example to display the current date and time. The calendar example in Listing 6.12,
* PrintCalendar.java, should give you some ideas on how to find the year, month, and day
*/
import java.util.Scanner;
public class Exercise6_24 {
/** Main method */
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //Create a Scanner object
//Prompt the user to enter
}
}
|
/*
* Copyright (C) 2017 GetMangos
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package eu.mangos.characters.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Embeddable;
/**
*
* @author GetMangos
*/
@Embeddable
public class GroupMemberPK implements Serializable {
@Basic(optional = false)
private int groupId;
@Basic(optional = false)
private int memberGuid;
public GroupMemberPK() {
}
public GroupMemberPK(int groupId, int memberGuid) {
this.groupId = groupId;
this.memberGuid = memberGuid;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public int getMemberGuid() {
return memberGuid;
}
public void setMemberGuid(int memberGuid) {
this.memberGuid = memberGuid;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) groupId;
hash += (int) memberGuid;
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof GroupMemberPK)) {
return false;
}
GroupMemberPK other = (GroupMemberPK) object;
if (this.groupId != other.groupId) {
return false;
}
if (this.memberGuid != other.memberGuid) {
return false;
}
return true;
}
@Override
public String toString() {
return "eu.mangos.characters.model.GroupMemberPK[ groupId=" + groupId + ", memberGuid=" + memberGuid + " ]";
}
}
|
package servlets;
import org.apache.log4j.Logger;
import org.eclipse.jetty.http.HttpStatus;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class UnsuccessfulPayServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(UnsuccessfulPayServlet.class);
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File file = new File("../resources/main/webcontent/failpage.html");
Document doc = Jsoup.parse(file,"UTF-8");
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write(doc.html());
StringBuilder stringBuilder = new StringBuilder();
Map<String,String[]> map = req.getParameterMap();
for (Map.Entry<String,String[]> entry : map.entrySet()){
stringBuilder.append(entry.getKey()).append(":").append(entry.getValue()[0]).append("\n");
}
log.info("Отказ платежа: "+stringBuilder.toString());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
log.error("вызван метод doGet");
doPost(req,resp);
}
}
|
package com.ojas.task.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.ojas.task.model.UserRoles;
public interface UserRolesRepo extends JpaRepository<UserRoles, Integer> {
// @Query("select a.role from UserRoles a, CustomUser b where b.userName = ?1 and a.roleId = b.")
// public List<UserRoles> findByUser(String name);
public UserRoles findByRole(String role);
public Optional<UserRoles> findByRoleId(Integer id);
}
|
package game.app.dtos.request;
import javax.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class ShopDto {
@NotBlank(message = "Direction cant be null or empty, try adding a direction")
private String direccion;
private int codigoPostal;
}
|
package com.company.c4q.whiteboardingexcercises;
/**
* This is slightly more difficult version of the famous FizzBuzz problem which is sometimes given as a first problem for job interviews. Consider the series of numbers beginning at start and running up to but not including end,
* so for example start = 1 and end = 5 gives the series 1, 2, 3, 4. Return a new String[] array containing the string form of these numbers (e.g. ["1", "2", "3" "4"]), except for multiples of 3, use "Fizz" instead of the number,
* for multiples of 5 use "Buzz", and for multiples of both 3 and 5 use "FizzBuzz". In Java, String.valueOf(xxx) will make the String form of an int or other type. This version is
* a little more complicated than the usual version since you have to allocate and index into an array instead of just printing, and we vary the start/end instead of just always doing 1..100.
*/
public class FizzBuzz {
public static void main(String[] args) {
for (String s : modifiedFizzBuzz(2, 16)) {
System.out.println(s);
}
}
static String[] modifiedFizzBuzz(int start, int end) {
String[] arr = new String[end - start];
int index = 0;
for (int i = start; i < end; i++) {
if (i % 3 == 0 && i % 5 == 0) {
arr[index] = "FizzBuzz";
} else if (i % 3 == 0) {
arr[index] = "Fizz";
} else if (i % 5 == 0) {
arr[index] = "Buzz";
} else {
arr[index] = String.valueOf(i);
}
index++;
}
return arr;
}
}
|
package it.univaq.rtv.controller;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
public class ControllerSceltaMappa {
private Label sceltaMappa;
private Button europa;
private Button usa;
private Button africa;
private Button sudAmerica;
private Button asia;
private Label sceltaGiocatori;
private Label inizioPartita;
private AnchorPane menu;
private Label scrittaGiocatori;
/**
* @param SceltaMappa
* @param Europa
* @param USA
* @param Africa
* @param Sud_America
* @param Asia
* @param SceltaGiocatori
* @param InizioPartita
* @param menu
* @param ScrittaGiocatori
*/
public ControllerSceltaMappa(Label SceltaMappa, Button Europa, Button USA, Button Africa, Button Sud_America, Button Asia, Label SceltaGiocatori, Label InizioPartita, AnchorPane menu, Label ScrittaGiocatori){
this.sceltaMappa =SceltaMappa;
this.sceltaGiocatori =SceltaGiocatori;
this.europa =Europa;
this.usa =USA;
this.africa =Africa;
this.sudAmerica =Sud_America;
this.asia =Asia;
this.inizioPartita =InizioPartita;
this.menu=menu;
this.scrittaGiocatori =ScrittaGiocatori;
this.europa.setVisible(false);
this.usa.setVisible(false);
this.africa.setVisible(false);
this.sudAmerica.setVisible(false);
this.asia.setVisible(false);
this.sceltaMappa.setVisible(false);
this.sceltaGiocatori.setVisible(false);
this.inizioPartita.setVisible(false);
this.menu.setVisible(true);
this.scrittaGiocatori.setVisible(false);
}
} |
package com.mysql.cj.xdevapi;
import java.math.BigDecimal;
public class JsonNumber implements JsonValue {
private String val = "null";
public Integer getInteger() {
return Integer.valueOf((new BigDecimal(this.val)).intValue());
}
public BigDecimal getBigDecimal() {
return new BigDecimal(this.val);
}
public JsonNumber setValue(String value) {
this.val = (new BigDecimal(value)).toString();
return this;
}
public String toString() {
return this.val;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\xdevapi\JsonNumber.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package org.alienideology.jcord.event.client.relation.request;
import org.alienideology.jcord.event.client.relation.RelationshipRemoveEvent;
import org.alienideology.jcord.handle.client.IClient;
import org.alienideology.jcord.handle.client.relation.IIncomingFriendRequest;
import org.alienideology.jcord.handle.client.relation.IRelationship;
/**
* @author AlienIdeology
*/
public class FriendRequestIgnoreEvent extends RelationshipRemoveEvent {
public FriendRequestIgnoreEvent(IClient client, int sequence, IRelationship relationship) {
super(client, sequence, relationship);
}
public IIncomingFriendRequest getIncomingFriendRequest() {
return getRelationship().getIncomingFriendRequest();
}
}
|
package com.DynamicProgramming;
import java.util.*;
import java.lang.*;
import java.io.*;
/* By Kapple */
class kadanes
{
public static void main (String[] args) throws IOException
{
//code
BufferedReader input = null;
input = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input/dummy"))));
int testCases = Integer.parseInt(input.readLine());
for(int i = 0; i < testCases; i++){
int numbers = Integer.parseInt(input.readLine());
int[] array = new int[numbers];
array = Arrays.stream(input.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int result = kadanes(numbers, array);
// int result = kadanes(array);
System.out.println(result);
}
}
public static int kadanes(int size, int[] array){
int sum = 0;
int maxSum = Integer.MIN_VALUE;
// int size = a.length;
for(int i = 0; i < size; i++){
if ( sum + array[i] <= 0 ){
if(maxSum < sum){
maxSum = sum;
}
sum = 0;
}else{
sum += array[i];
}
}
if(maxSum < sum){
maxSum = sum;
}
return maxSum;
}
// static int kadanes(int a[])
// {
// int size = a.length;
// int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;
//
// for (int i = 0; i < size; i++)
// {
// max_ending_here = max_ending_here + a[i];
// if (max_so_far < max_ending_here)
// max_so_far = max_ending_here;
// if (max_ending_here < 0)
// max_ending_here = 0;
// }
// return max_so_far;
// }
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.