text
stringlengths
10
2.72M
package com.project.model; public class Field { String field; String fieldType; String fieldLength; String isMandatoryField; public String getField() { return field; } public void setField(String field) { this.field = field; } public String getFieldType() { return fieldType; } public void setFieldType(String fieldType) { this.fieldType = fieldType; } public String getFieldLength() { return fieldLength; } public void setFieldLength(String fieldLength) { this.fieldLength = fieldLength; } public String getIsMandatoryField() { return isMandatoryField; } public void setIsMandatoryField(String isMandatoryField) { this.isMandatoryField = isMandatoryField; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package co.th.aten.network.entity; import java.io.Serializable; import java.util.Collection; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * * @author Atenpunk */ @Entity @Table(name = "master_official_document") @NamedQueries({ @NamedQuery(name = "MasterOfficialDocument.findAll", query = "SELECT m FROM MasterOfficialDocument m"), @NamedQuery(name = "MasterOfficialDocument.findByOffDocId", query = "SELECT m FROM MasterOfficialDocument m WHERE m.offDocId = :offDocId"), @NamedQuery(name = "MasterOfficialDocument.findByDescTh", query = "SELECT m FROM MasterOfficialDocument m WHERE m.descTh = :descTh"), @NamedQuery(name = "MasterOfficialDocument.findByDescEn", query = "SELECT m FROM MasterOfficialDocument m WHERE m.descEn = :descEn"), @NamedQuery(name = "MasterOfficialDocument.findByDescLao", query = "SELECT m FROM MasterOfficialDocument m WHERE m.descLao = :descLao"), @NamedQuery(name = "MasterOfficialDocument.findByCreateBy", query = "SELECT m FROM MasterOfficialDocument m WHERE m.createBy = :createBy"), @NamedQuery(name = "MasterOfficialDocument.findByCreateDate", query = "SELECT m FROM MasterOfficialDocument m WHERE m.createDate = :createDate"), @NamedQuery(name = "MasterOfficialDocument.findByUpdateBy", query = "SELECT m FROM MasterOfficialDocument m WHERE m.updateBy = :updateBy"), @NamedQuery(name = "MasterOfficialDocument.findByUpdateDate", query = "SELECT m FROM MasterOfficialDocument m WHERE m.updateDate = :updateDate")}) public class MasterOfficialDocument implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "off_doc_id") private Integer offDocId; @Column(name = "desc_th") private String descTh; @Column(name = "desc_en") private String descEn; @Column(name = "desc_lao") private String descLao; @Column(name = "create_by") private Integer createBy; @Column(name = "create_date") @Temporal(TemporalType.TIMESTAMP) private Date createDate; @Column(name = "update_by") private Integer updateBy; @Column(name = "update_date") @Temporal(TemporalType.TIMESTAMP) private Date updateDate; @OneToMany(mappedBy = "officialDocumentId") private Collection<MemberCustomer> memberCustomerCollection; public MasterOfficialDocument() { } public MasterOfficialDocument(Integer offDocId) { this.offDocId = offDocId; } public Integer getOffDocId() { return offDocId; } public void setOffDocId(Integer offDocId) { this.offDocId = offDocId; } public String getDescTh() { return descTh; } public void setDescTh(String descTh) { this.descTh = descTh; } public String getDescEn() { return descEn; } public void setDescEn(String descEn) { this.descEn = descEn; } public String getDescLao() { return descLao; } public void setDescLao(String descLao) { this.descLao = descLao; } public Integer getCreateBy() { return createBy; } public void setCreateBy(Integer createBy) { this.createBy = createBy; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Integer getUpdateBy() { return updateBy; } public void setUpdateBy(Integer updateBy) { this.updateBy = updateBy; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public Collection<MemberCustomer> getMemberCustomerCollection() { return memberCustomerCollection; } public void setMemberCustomerCollection(Collection<MemberCustomer> memberCustomerCollection) { this.memberCustomerCollection = memberCustomerCollection; } @Override public int hashCode() { int hash = 0; hash += (offDocId != null ? offDocId.hashCode() : 0); 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 MasterOfficialDocument)) { return false; } MasterOfficialDocument other = (MasterOfficialDocument) object; if ((this.offDocId == null && other.offDocId != null) || (this.offDocId != null && !this.offDocId.equals(other.offDocId))) { return false; } return true; } @Override public String toString() { return "co.th.aten.network.entity.MasterOfficialDocument[offDocId=" + offDocId + "]"; } }
package com.example.tanapon.computerproject1; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; public class ServiceGridAdapter extends BaseAdapter { ArrayList names; public static Activity activity; private DatabaseReference mDatabase; public ServiceGridAdapter(Activity activity, ArrayList names) { this.activity = activity; this.names = names; } @Override public int getCount() { return names.size(); } @Override public Object getItem(int position) { return names.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View v, ViewGroup parent) { //Firebase Database mDatabase = FirebaseDatabase.getInstance().getReference(); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(activity); int defaultValue = 0; long highScore = sharedPref.getInt("saved_high_score", defaultValue); final String user_log = "table_" + String.valueOf(highScore); if (v == null) { LayoutInflater vi = LayoutInflater.from(activity); v = vi.inflate(R.layout.service_grid_layout, null); } TextView textView = (TextView) v.findViewById(R.id.namePlacer); ImageView imageView = (ImageView) v.findViewById(R.id.imageHolder); if (names.get(position).toString().equals("เปลี่ยนกระทะ")) { imageView.setImageResource(R.mipmap.ic_attendance); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage("ท่านต้องการเปลี่ยนกระทะ"); builder.setPositiveButton("ตกลง", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Toast.makeText(activity, "กรุณารอสักครู่", Toast.LENGTH_SHORT).show(); mDatabase.child("requirement").child(user_log).push().setValue("เปลี่ยนกระทะ"); } }); builder.setNegativeButton("ยกเลิก", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //dialog.dismiss(); } }); builder.show(); } }); Animation anim = new ScaleAnimation( 0.95f, 1f, // Start and end values for the X axis scaling 0.95f, 1f, // Start and end values for the Y axis scaling Animation.RELATIVE_TO_SELF, 0.5f, // Pivot point of X scaling Animation.RELATIVE_TO_SELF, 0.5f); // Pivot point of Y scaling anim.setFillAfter(true); // Needed to keep the result of the animation anim.setDuration(2000); anim.setRepeatMode(Animation.INFINITE); anim.setRepeatCount(Animation.INFINITE); imageView.startAnimation(anim); } else if (names.get(position).toString().equals("เติมถ่าน")) { imageView.setImageResource(R.mipmap.ic_schedule); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage("ท่านต้องการเติมถ่าน"); builder.setPositiveButton("ตกลง", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Toast.makeText(activity, "กรุณารอสักครู่", Toast.LENGTH_SHORT).show(); mDatabase.child("requirement").child(user_log).push().setValue("เติมถ่าน"); } }); builder.setNegativeButton("ยกเลิก", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //dialog.dismiss(); } }); builder.show(); } }); Animation anim = new ScaleAnimation( 0.95f, 1f, // Start and end values for the X axis scaling 0.95f, 1f, // Start and end values for the Y axis scaling Animation.RELATIVE_TO_SELF, 0.5f, // Pivot point of X scaling Animation.RELATIVE_TO_SELF, 0.5f); // Pivot point of Y scaling anim.setFillAfter(true); // Needed to keep the result of the animation anim.setDuration(2000); anim.setRepeatMode(Animation.INFINITE); anim.setRepeatCount(Animation.INFINITE); imageView.startAnimation(anim); } else if (names.get(position).toString().equals("เติมน้ำจิ้ม")) { imageView.setImageResource(R.mipmap.ic_notes); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage("ท่านต้องการเติมน้ำจิ้ม"); builder.setPositiveButton("ตกลง", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Toast.makeText(activity, "กรุณารอสักครู่", Toast.LENGTH_SHORT).show(); mDatabase.child("requirement").child(user_log).push().setValue("เติมน้ำจิ้ม"); } }); builder.setNegativeButton("ยกเลิก", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //dialog.dismiss(); } }); builder.show(); } }); Animation anim = new ScaleAnimation( 0.95f, 1f, // Start and end values for the X axis scaling 0.95f, 1f, // Start and end values for the Y axis scaling Animation.RELATIVE_TO_SELF, 0.5f, // Pivot point of X scaling Animation.RELATIVE_TO_SELF, 0.5f); // Pivot point of Y scaling anim.setFillAfter(true); // Needed to keep the result of the animation anim.setDuration(2000); anim.setRepeatMode(Animation.INFINITE); anim.setRepeatCount(Animation.INFINITE); imageView.startAnimation(anim); } else if (names.get(position).toString().equals("เติมกระดาษ")) { imageView.setImageResource(R.mipmap.ic_profile); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage("ท่านต้องการเเติมกระดาษทิชชู่"); builder.setPositiveButton("ตกลง", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Toast.makeText(activity, "กรุณารอสักครู่", Toast.LENGTH_SHORT).show(); mDatabase.child("requirement").child(user_log).push().setValue("เติมกระดาษ"); } }); builder.setNegativeButton("ยกเลิก", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //dialog.dismiss(); } }); builder.show(); } }); Animation anim = new ScaleAnimation( 0.95f, 1f, // Start and end values for the X axis scaling 0.95f, 1f, // Start and end values for the Y axis scaling Animation.RELATIVE_TO_SELF, 0.5f, // Pivot point of X scaling Animation.RELATIVE_TO_SELF, 0.5f); // Pivot point of Y scaling anim.setFillAfter(true); // Needed to keep the result of the animation anim.setDuration(2000); anim.setRepeatMode(Animation.INFINITE); anim.setRepeatCount(Animation.INFINITE); imageView.startAnimation(anim); } else if (names.get(position).toString().equals("เติมน้ำซุป")) { imageView.setImageResource(R.mipmap.ic_capa); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage("ท่านต้องการเเติมน้ำซุป"); builder.setPositiveButton("ตกลง", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Toast.makeText(activity, "กรุณารอสักครู่", Toast.LENGTH_SHORT).show(); mDatabase.child("requirement").child(user_log).push().setValue("เติมน้ำซุป"); } }); builder.setNegativeButton("ยกเลิก", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //dialog.dismiss(); } }); builder.show(); } }); Animation anim = new ScaleAnimation( 0.95f, 1f, // Start and end values for the X axis scaling 0.95f, 1f, // Start and end values for the Y axis scaling Animation.RELATIVE_TO_SELF, 0.5f, // Pivot point of X scaling Animation.RELATIVE_TO_SELF, 0.5f); // Pivot point of Y scaling anim.setFillAfter(true); // Needed to keep the result of the animation anim.setDuration(2000); anim.setRepeatMode(Animation.INFINITE); anim.setRepeatCount(Animation.INFINITE); imageView.startAnimation(anim); } textView.setText(names.get(position).toString()); return v; } }
import java.net.*; import java.io.*; import java.util.*; import java.util.concurrent.*; //**************************************************************************** public class Joueur{ private String id; private int port; private boolean pret; private int score; private int y; private int x; private int game; public Joueur(String id, int port){ this.id = id; this.port = port; this.score = 0; this.pret = false; } public String getId(){ return this.id; } public void setId(String id){ this.id = id; } public int getGame(){ return this.game; } public void setGame(int g){ this.game = g; } public int getX(){ return this.x; } public void setX(int x){ this.x = x; } public int getY(){ return this.y; } public void setY(int y){ this.y = y; } public boolean getPret(){ return this.pret; } public void setPret(boolean pret){ this.pret = pret; } public void setScore(int n){ this.score = n; } public int getScore(){ return this.score; } public int getPort(){ return this.port; } public void setPort(int port){ this.port = port; } }
/* * [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 de.hybris.platform.cmsfacades.common.validator.impl; import de.hybris.platform.cms2.servicelayer.services.admin.CMSAdminSiteService; import de.hybris.platform.cmsfacades.common.validator.LocalizedTypeValidator; import de.hybris.platform.cmsfacades.constants.CmsfacadesConstants; import de.hybris.platform.core.model.media.MediaModel; import de.hybris.platform.servicelayer.exceptions.AmbiguousIdentifierException; import de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException; import de.hybris.platform.servicelayer.media.MediaService; import java.util.Objects; import org.springframework.beans.factory.annotation.Required; import org.springframework.validation.Errors; /** * Default validator to use for validating localized attributes of type media. This implementation uses the * {@link MediaService} and the {@link CMSAdminSiteService} to verify whether a given media is valid or not. */ public class LocalizedMediaValidator implements LocalizedTypeValidator { private MediaService mediaService; private CMSAdminSiteService cmsAdminSiteService; /* * Suppress sonar warning (squid:S1166 | Exception handlers should preserve the original exceptions) : It is * perfectly acceptable not to handle "e" here */ @SuppressWarnings("squid:S1166") @Override public void validate(final String language, final String fieldName, final String mediaCode, final Errors errors) { try { if (!Objects.isNull(mediaCode)) { final MediaModel media = getMediaService().getMedia(getCmsAdminSiteService().getActiveCatalogVersion(), mediaCode); if (Objects.isNull(media)) { reject(language, fieldName, CmsfacadesConstants.INVALID_MEDIA_CODE_L10N, errors); } } } catch (UnknownIdentifierException | AmbiguousIdentifierException e) { reject(language, fieldName, CmsfacadesConstants.INVALID_MEDIA_CODE_L10N, errors); } } @Override public void reject(final String language, final String fieldName, final String errorCode, final Errors errors) { errors.rejectValue(fieldName, errorCode, new Object[] { language }, null); } protected MediaService getMediaService() { return mediaService; } @Required public void setMediaService(final MediaService mediaService) { this.mediaService = mediaService; } protected CMSAdminSiteService getCmsAdminSiteService() { return cmsAdminSiteService; } @Required public void setCmsAdminSiteService(final CMSAdminSiteService cmsAdminSiteService) { this.cmsAdminSiteService = cmsAdminSiteService; } }
import java.net.URI; import java.net.URISyntaxException; /** * Created by soomin on 2015. 12. 4.. */ public class TestURI { public static void main(String[] args) throws URISyntaxException { URI uri = new URI("http://example.com/foo/bar/42?param=true"); String[] sa = uri.getPath().split("/"); System.out.println(sa[1]); System.out.println(uri.getPath()); } }
package quiz; import java.util.Scanner; public class Quiz10 { public static void main(String[] args) { /* * 정수 3개를 받아서 큰값, 중간, 작은값을 구분하면 됩니다. (단, 세값이 같은 경우는 예외로 한다 ) */ Scanner scan = new Scanner(System.in); System.out.print("> "); int a = scan.nextInt(); System.out.print("> "); int b = scan.nextInt(); System.out.print("> "); int c = scan.nextInt(); int max = 0, mid =0, min=0; if(a > b && a>c) { max = a; if(b>c) { mid = b; min = c; }else { mid = c; min = b; } }else if(b>a && b>c) { max = b; if(a>c) { mid = a; min = c; }else { mid = c; min = a; } }else if(c>a && c>b) { max = c; if(a>b) { mid = a; min = b; }else { mid = b; min = a; } } System.out.println("max : " + max); System.out.println("mid : " + mid); System.out.println("min : " + min); scan.close(); } }
/** * @(#)RpcDecoder.java, 2020/7/14. * <p/> * Copyright 2020 Netease, Inc. All rights reserved. * NETEASE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.xx.rpc.protocol; import com.xx.rpc.util.ProtostuffSerialization; import com.xx.rpc.util.Serialization; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.util.List; public class RpcDecoder extends ByteToMessageDecoder { private Class<?> genericClass; public RpcDecoder(Class<?> genericClass){ this.genericClass = genericClass; } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // 防止黏包 if (in.readableBytes() < 4) return; in.markReaderIndex(); int dataLength = in.readInt(); if (dataLength < 0) ctx.close(); if (in.readableBytes() < dataLength){ in.resetReaderIndex(); return; } byte[] data = new byte[dataLength]; in.readBytes(data); Serialization serialization = new ProtostuffSerialization(); Object obj = serialization.deserialize(data,genericClass); out.add(obj); } }
import java.awt.image.BufferedImage; import java.io.File; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.Image; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JFileChooser; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JTextPane; import javax.swing.border.Border; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.JLabel; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.ImageIcon; public class Window2 { private JFrame frame; private final JButton btnNewButton = new JButton("Back"); private JLabel Label1; private JLabel Label2; private JLabel Label3; private JLabel Label4; private JLabel Label5; private JLabel Label6; private JLabel Label1_1; private JLabel Label2_1; private JLabel Label3_1; private JLabel Label4_1; private JLabel Label5_1; private JLabel Label6_1; private JLabel Label1_big; private JLabel Label2_big; private JLabel Label3_big; private JLabel Label4_big; private JLabel Label5_big; private JLabel Label6_big; private JLabel rezultat1; private JLabel rezultat2; private JLabel rezultat3; private JLabel rezultat4; private JLabel rezultat5; private JLabel rezultat6; private JTextPane text; private JTextPane textSave; private JTextPane textTitlu1; private JTextPane textTitlu2; private JTextPane textTitlu3; private JTextPane textTitlu4; private JTextPane textTitlu5; private JTextPane textTitlu6; private JTextPane textRezultat1; private JTextPane textRezultat2; private JTextPane textRezultat3; private JTextPane textRezultat4; private JTextPane textRezultat5; private JTextPane textRezultat6; private JButton saveButton; public void setFrame() { this.frame.setLocationRelativeTo(null); } public void setVisible(boolean input){ frame.setVisible(input); } public void setImage(String path, JLabel j) { BufferedImage img1 = null; try { img1 = ImageIO.read(new File(path)); } catch (Exception exce) { exce.printStackTrace(); } Image dimg1 = img1.getScaledInstance(j.getWidth(), j.getHeight(),Image.SCALE_SMOOTH); j.setIcon(new ImageIcon(dimg1)); } public void setImage(BufferedImage img, JLabel label) { Image imagine = img.getScaledInstance(label.getWidth(), label.getHeight(),Image.SCALE_SMOOTH); label.setIcon(new ImageIcon(imagine)); } public JLabel getLabel1_big() { return Label1_big; } public JLabel getLabel2_big() { return Label2_big; } public JLabel getLabel3_big() { return Label3_big; } public JLabel getLabel4_big() { return Label4_big; } public JLabel getLabel5_big() { return Label5_big; } public JLabel getLabel6_big() { return Label6_big; } public JLabel rezultat1() { return rezultat1; } public JLabel rezultat2() { return rezultat2; } public JLabel rezultat3() { return rezultat3; } public JLabel rezultat4() { return rezultat4; } public JLabel rezultat5() { return rezultat5; } public JLabel rezultat6() { return rezultat6; } public JLabel getLabel1() { return Label1; } public JLabel getLabel2() { return Label2; } public JLabel getLabel3() { return Label3; } public JLabel getLabel4() { return Label4; } public JLabel getLabel5() { return Label5; } public JLabel getLabel6() { return Label6; } public JLabel getLabel1_1() { return Label1_1; } public JLabel getLabel2_1() { return Label2_1; } public JLabel getLabel3_1() { return Label3_1; } public JLabel getLabel4_1() { return Label4_1; } public JLabel getLabel5_1() { return Label5_1; } public JLabel getLabel6_1() { return Label6_1; } public JTextPane getPaneText() { return text; } public JTextPane getPaneTextTitlu1() { return textTitlu1; } public JTextPane getPaneTextTitlu2() { return textTitlu2; } public JTextPane getPaneTextTitlu3() { return textTitlu3; } public JTextPane getPaneTextTitlu4() { return textTitlu4; } public JTextPane getPaneTextTitlu5() { return textTitlu5; } public JTextPane getPaneTextTitlu6() { return textTitlu6; } public JTextPane getPaneRezultat1() { return textRezultat1; } public JTextPane getPaneRezultat2() { return textRezultat2; } public JTextPane getPaneRezultat3() { return textRezultat3; } public JTextPane getPaneRezultat4() { return textRezultat4; } public JTextPane getPaneRezultat5() { return textRezultat5; } public JTextPane getPaneRezultat6() { return textRezultat6; } /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Window2 window = new Window2(); window.frame.setVisible(true); window.frame.setLocationRelativeTo(null); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Window2() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 1084, 819); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //directory_interface d1 = new directory_interface(); //d1.setVisible(true); frame.setVisible(false); } }); btnNewButton.setBounds(23, 11, 120, 31); frame.getContentPane().add(btnNewButton); Border border = BorderFactory.createLineBorder(Color.black, 2); Border border2 = BorderFactory.createLineBorder(Color.DARK_GRAY, 2); Label1 = new JLabel(""); Label1.setBounds(23, 162, 130, 165); Label1.setBorder(border); frame.getContentPane().add(Label1); Label2 = new JLabel(""); Label2.setBounds(206, 162, 130, 165); Label2.setBorder(border); frame.getContentPane().add(Label2); Label3 = new JLabel(""); Label3.setBounds(380, 162, 130, 165); Label3.setBorder(border); frame.getContentPane().add(Label3); Label4 = new JLabel(""); Label4.setBounds(560, 162, 130, 165); Label4.setBorder(border); frame.getContentPane().add(Label4); Label5 = new JLabel(""); Label5.setBounds(738, 162, 130, 165); Label5.setBorder(border); frame.getContentPane().add(Label5); Label6 = new JLabel(""); Label6.setBounds(918, 162, 130, 165); Label6.setBorder(border); frame.getContentPane().add(Label6); Label1_1 = new JLabel(""); Label1_1.setBounds(23, 348, 130, 165); Label1_1.setBorder(border); frame.getContentPane().add(Label1_1); Label2_1 = new JLabel(""); Label2_1.setBounds(206, 348, 130, 165); Label2_1.setBorder(border); frame.getContentPane().add(Label2_1); Label3_1 = new JLabel(""); Label3_1.setBounds(380, 348, 130, 165); Label3_1.setBorder(border); frame.getContentPane().add(Label3_1); Label4_1 = new JLabel(""); Label4_1.setBounds(560, 348, 130, 165); Label4_1.setBorder(border); frame.getContentPane().add(Label4_1); Label5_1 = new JLabel(""); Label5_1.setBounds(738, 348, 130, 165); Label5_1.setBorder(border); frame.getContentPane().add(Label5_1); Label6_1 = new JLabel(""); Label6_1.setBounds(918, 348, 130, 165); Label6_1.setBorder(border); frame.getContentPane().add(Label6_1); Label1_big = new JLabel(""); Label1_big.setBounds(10, 73, 159, 700); Label1_big.setBorder(border2); frame.getContentPane().add(Label1_big); Label2_big = new JLabel(""); Label2_big.setBounds(190, 73, 159, 700); Label2_big.setBorder(border2); frame.getContentPane().add(Label2_big); Label3_big = new JLabel(""); Label3_big.setBounds(368, 73, 159, 700); Label3_big.setBorder(border2); frame.getContentPane().add(Label3_big); Label4_big = new JLabel(""); Label4_big.setBounds(545, 73, 159, 700); Label4_big.setBorder(border2); frame.getContentPane().add(Label4_big); Label5_big = new JLabel(""); Label5_big.setBounds(724, 73, 159, 700); Label5_big.setBorder(border2); frame.getContentPane().add(Label5_big); Label6_big = new JLabel(""); Label6_big.setBounds(905, 73, 159, 700); Label6_big.setBorder(border2); frame.getContentPane().add(Label6_big); text = new JTextPane(); text.setBounds(171, 10, 492, 48); frame.getContentPane().add(text); text.setBackground(frame.getBackground()); SimpleAttributeSet attribs3 = new SimpleAttributeSet(); StyleConstants.setAlignment(attribs3, StyleConstants.ALIGN_CENTER); StyleConstants.setBold(attribs3, true); StyleConstants.setFontSize(attribs3, 24); StyleConstants.setForeground(attribs3, Color.BLUE); StyleConstants.setFontFamily(attribs3, Font.MONOSPACED); text.setEditable(false); text.setParagraphAttributes(attribs3, true); frame.getContentPane().add(text); SimpleAttributeSet attrib = new SimpleAttributeSet(); StyleConstants.setAlignment(attrib, StyleConstants.ALIGN_CENTER); StyleConstants.setBold(attrib, true); StyleConstants.setFontSize(attrib, 15); StyleConstants.setBackground(attrib, Color.WHITE); StyleConstants.setForeground(attrib, Color.BLUE); StyleConstants.setFontFamily(attrib, Font.MONOSPACED); SimpleAttributeSet attrib4 = new SimpleAttributeSet(); StyleConstants.setAlignment(attrib4, StyleConstants.ALIGN_CENTER); StyleConstants.setBold(attrib4, true); StyleConstants.setFontSize(attrib4, 15); StyleConstants.setBackground(attrib4, Color.WHITE); StyleConstants.setForeground(attrib4, Color.RED); StyleConstants.setFontFamily(attrib4, Font.MONOSPACED); textSave = new JTextPane(); textSave.setBounds(754, 0, 306, 31); textSave.setText("Save the entire top as CSV File !"); textSave.setParagraphAttributes(attrib4, true); textSave.setEditable(false); frame.getContentPane().add(textSave); textSave.setBackground(frame.getBackground()); saveButton = new JButton("Save File"); saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Save a File "); chooser.setSelectedFile(new File("rezult.csv")); FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV Files", "csv", "CSV"); chooser.setFileFilter(filter); int save = chooser.showSaveDialog(frame); if (save == JFileChooser.APPROVE_OPTION) { String dir = chooser.getSelectedFile().getAbsolutePath(); Path p1 = Paths.get("src\\data\\rezult.csv"); Path p2 = Paths.get(dir); CopyOption[] options = new CopyOption[]{ StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES }; try { Files.copy(p1, p2,options); } catch (Exception ex) { ex.printStackTrace(); } } } }); saveButton.setBounds(859, 38, 141, 25); frame.getContentPane().add(saveButton); textTitlu1 = new JTextPane(); textTitlu1.setBounds(23, 87, 130, 65); textTitlu1.setEditable(false); textTitlu1.setParagraphAttributes(attrib, true); textTitlu1.setBackground(frame.getBackground()); textTitlu1.setBorder(border2); frame.getContentPane().add(textTitlu1); textTitlu2 = new JTextPane(); textTitlu2.setBounds(206, 87, 130, 65); textTitlu2.setParagraphAttributes(attrib, true); textTitlu2.setEditable(false); textTitlu2.setBackground(frame.getBackground()); textTitlu2.setBorder(border2); frame.getContentPane().add(textTitlu2); textTitlu3 = new JTextPane(); textTitlu3.setBounds(380, 87, 130, 65); textTitlu3.setParagraphAttributes(attrib, true); textTitlu3.setBackground(frame.getBackground()); textTitlu3.setBorder(border2); textTitlu3.setEditable(false); frame.getContentPane().add(textTitlu3); textTitlu4 = new JTextPane(); textTitlu4.setBounds(560, 87, 130, 65); textTitlu4.setParagraphAttributes(attrib, true); textTitlu4.setBackground(frame.getBackground()); textTitlu4.setBorder(border2); textTitlu4.setEditable(false); frame.getContentPane().add(textTitlu4); textTitlu5 = new JTextPane(); textTitlu5.setBounds(738, 87, 130, 65); textTitlu5.setParagraphAttributes(attrib, true); textTitlu5.setBackground(frame.getBackground()); textTitlu5.setBorder(border2); textTitlu5.setEditable(false); frame.getContentPane().add(textTitlu5); textTitlu6 = new JTextPane(); textTitlu6.setBounds(918, 88, 130, 64); textTitlu6.setParagraphAttributes(attrib, true); textTitlu6.setBackground(frame.getBackground()); textTitlu6.setBorder(border2); textTitlu6.setEditable(false); frame.getContentPane().add(textTitlu6); rezultat1 = new JLabel(""); rezultat1.setBounds(23, 562, 130, 197); rezultat1.setBorder(border); frame.getContentPane().add(rezultat1); rezultat2 = new JLabel(""); rezultat2.setBounds(206, 562, 130, 197); rezultat2.setBorder(border); frame.getContentPane().add(rezultat2); rezultat3 = new JLabel(""); rezultat3.setBounds(380, 562, 130, 197); rezultat3.setBorder(border); frame.getContentPane().add(rezultat3); rezultat4 = new JLabel(""); rezultat4.setBounds(560, 562, 130, 197); rezultat4.setBorder(border); frame.getContentPane().add(rezultat4); rezultat5 = new JLabel(""); rezultat5.setBounds(738, 562, 130, 197); rezultat5.setBorder(border); frame.getContentPane().add(rezultat5); rezultat6 = new JLabel(""); rezultat6.setBounds(918, 562, 130, 197); rezultat6.setBorder(border); frame.getContentPane().add(rezultat6); SimpleAttributeSet attribb = new SimpleAttributeSet(); StyleConstants.setAlignment(attribb, StyleConstants.ALIGN_CENTER); StyleConstants.setBold(attribb, true); StyleConstants.setFontSize(attribb, 13); StyleConstants.setBackground(attribb, Color.WHITE); StyleConstants.setForeground(attribb, Color.BLUE); StyleConstants.setFontFamily(attribb, Font.MONOSPACED); textRezultat1 = new JTextPane(); textRezultat1.setBounds(23, 515, 130, 36); textRezultat1.setParagraphAttributes(attribb, true); textRezultat1.setBackground(frame.getBackground()); textRezultat1.setEditable(false); frame.getContentPane().add(textRezultat1); textRezultat2 = new JTextPane(); textRezultat2.setBounds(206, 515, 130, 36); textRezultat2.setParagraphAttributes(attribb, true); textRezultat2.setBackground(frame.getBackground()); textRezultat2.setEditable(false); frame.getContentPane().add(textRezultat2); textRezultat3 = new JTextPane(); textRezultat3.setBounds(380, 515, 130, 36); textRezultat3.setParagraphAttributes(attribb, true); textRezultat3.setBackground(frame.getBackground()); textRezultat3.setEditable(false); frame.getContentPane().add(textRezultat3); textRezultat4 = new JTextPane(); textRezultat4.setBounds(560, 515, 130, 36); textRezultat4.setParagraphAttributes(attribb, true); textRezultat4.setBackground(frame.getBackground()); textRezultat4.setEditable(false); frame.getContentPane().add(textRezultat4); textRezultat5 = new JTextPane(); textRezultat5.setBounds(738, 515, 130, 36); textRezultat5.setParagraphAttributes(attribb, true); textRezultat5.setBackground(frame.getBackground()); textRezultat5.setEditable(false); frame.getContentPane().add(textRezultat5); textRezultat6 = new JTextPane(); textRezultat6.setBounds(918, 515, 130, 36); textRezultat6.setParagraphAttributes(attribb, true); textRezultat6.setBackground(frame.getBackground()); textRezultat6.setEditable(false); frame.getContentPane().add(textRezultat6); } }
package com.santander.bi.DAO; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.santander.bi.model.ChartProc; @Repository @SuppressWarnings({ "unchecked"}) public class ChartProcDAOImpl extends AbstractBaseDAO implements ChartProcDAO{ Logger logger = Logger.getLogger(getClass()); @Autowired SessionFactory sessionFactory; /* (non-Javadoc) * @see com.santander.bi.DAO.ChartProcDAO#getAll(java.lang.Integer) */ @Override public List<ChartProc> getAll(Integer idProceso) { List<ChartProc> usuarioList = null; try { session = getCurrenSessionFactory(); Query query = session.createQuery("from ChartProc us where us.idProceso=:idProceso"); query.setParameter("idProceso", idProceso); usuarioList = query.list(); for(ChartProc p : usuarioList){ logger.info("Person List::"+p); } }catch(Exception ex) { ex.printStackTrace(); } return usuarioList; } /* (non-Javadoc) * @see com.santander.bi.DAO.ChartProcDAO#get(int) */ @Override public ChartProc get(int id){ session = getCurrenSessionFactory(); ChartProc p = (ChartProc) session.load(ChartProc.class, new Integer(id)); logger.info("Person loaded successfully, Person details="+p); return p; } /* (non-Javadoc) * @see com.santander.bi.DAO.ChartProcDAO#getAll() */ @Override public List<ChartProc> getAll() { List<ChartProc> usuarioList = null; try { session = getCurrenSessionFactory(); usuarioList = session.createQuery("from ChartProc").list(); for(ChartProc p : usuarioList){ logger.info("Person List::"+p); } }catch(Exception ex) { ex.printStackTrace(); } return usuarioList; } /* (non-Javadoc) * @see com.santander.bi.DAO.ChartProcDAO#save(com.santander.bi.model.ChartProc) */ @Override public ChartProc save(ChartProc t) { try { session = getCurrenSessionFactory(); try { //session.beginTransaction(); session.persist(t); //session.getTransaction().commit(); //session.close(); logger.info("ChartProc saved successfully, Person Details="+t); }catch(Exception ex) { ex.printStackTrace(); //session.getTransaction().rollback(); //SessionFactorySingleton.limpiaSession(this.sessionFactory); return null; } }catch(Exception ex) { ex.printStackTrace(); return null; } return t; } /* (non-Javadoc) * @see com.santander.bi.DAO.ChartProcDAO#update(com.santander.bi.model.ChartProc) */ @Override public ChartProc update(ChartProc t) { try { session = getCurrenSessionFactory(); try { //session.beginTransaction(); t = (ChartProc)session.merge(t); session.saveOrUpdate(t); //session.getTransaction().commit(); //session.close(); logger.info("ChartProc updated successfully, Person Details="+t); }catch(Exception ex) { ex.printStackTrace(); //session.getTransaction().rollback(); //SessionFactorySingleton.limpiaSession(this.sessionFactory); return null; } }catch(Exception ex) { ex.printStackTrace(); return null; } return t; } /* (non-Javadoc) * @see com.santander.bi.DAO.ChartProcDAO#delete(int) */ @Override public ChartProc delete(int id) { ChartProc p= null; try { session = getCurrenSessionFactory(); p = (ChartProc) session.load(ChartProc.class, new Integer(id)); if(null != p){ try { //session.beginTransaction(); session.delete(p); //session.getTransaction().commit(); //session.close(); logger.info("ChartProc updated successfully, Person Details="+p); }catch(Exception ex) { ex.printStackTrace(); //session.getTransaction().rollback(); } } }catch(Exception ex) { ex.printStackTrace(); return null; } logger.info("Person deleted successfully, person details="+p); return p; } /* (non-Javadoc) * @see com.santander.bi.DAO.ChartProcDAO#delete(com.santander.bi.model.ChartProc) */ @Override public ChartProc delete(ChartProc p) { // TODO Auto-generated method stub try { session = getCurrenSessionFactory(); if(null != p){ try { p = (ChartProc)session.merge(p); //session.beginTransaction(); session.delete(p); //session.getTransaction().commit(); //session.close(); logger.info("ChartProc updated successfully, Person Details="+p); }catch(Exception ex) { ex.printStackTrace(); //session.getTransaction().rollback(); //SessionFactorySingleton.limpiaSession(this.sessionFactory); return null; } } }catch(Exception ex) { ex.printStackTrace(); return null; } logger.info("Person deleted successfully, person details="+p); return p; } }
package me.bemind.fingerprinthelper; import android.hardware.fingerprint.FingerprintManager; /** * Created by angelomoroni on 06/02/17. */ public interface AuthenticationCallback { void onAuthenticationError(int errMsgId, CharSequence errString) ; void onAuthenticationHelp(int helpMsgId, CharSequence helpString); void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result); void onAuthenticationFailed(); }
package com.vibexie.jianai.Utils; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class TimeUtil { /** * 获取当前标准时间 格式 年:月:日 时:分:秒 * @return */ public static String getCurrentStandardTime(){ Date date=new Date(); DateFormat dateFormat=new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); return dateFormat.format(date); } public static String millisTimeToStandardTime(long millisTime){ Date date=new Date(millisTime); DateFormat dateFormat=new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); return dateFormat.format(date); } }
package com.company.carseller.action; import com.company.carseller.database.LanguagesDAO; import com.company.carseller.entity.Transmission; import com.company.carseller.database.TransmissionDAO; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class AddTransmissionAction implements Action { @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); LanguagesDAO languagesDAO = new LanguagesDAO(); String language = (String) session.getAttribute("lang"); int languageId = languagesDAO.getLanguageIdByLocale(language); TransmissionDAO transmissionDAO = new TransmissionDAO(); Transmission transmission = new Transmission(); String newTransmission = request.getParameter("newTransmission"); transmission.setLanguageId(languageId); transmission.setTransmission(newTransmission); transmissionDAO.insert(transmission); RequestDispatcher requestDispatcher = request.getRequestDispatcher("/pages/result.jsp"); requestDispatcher.forward(request, response); } }
package com.lucasgr7.hexagontest.controller.contract; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import com.lucasgr7.hexagontest.controller.contract.dto.DtoSaveVehicleTypeRequest; import com.lucasgr7.hexagontest.controller.contract.dto.DtoUpdateVehicleTypeRequest; @Component public interface IVehicleTypeController { public ResponseEntity<?> save(DtoSaveVehicleTypeRequest dto); public ResponseEntity<?> update(DtoUpdateVehicleTypeRequest dto); public ResponseEntity<?> delete(Integer id); public ResponseEntity<?> search(Integer id, String name); public ResponseEntity<?> all(); }
package com.shubh.javaworld; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PalindromicPair { public List<List<Integer>> palindromePairs(String[] words) { List<List<Integer>> results = new ArrayList<List<Integer>>(); if (words == null) { return results; } Map<String, Integer> wordMap = new HashMap<String, Integer>(); for (int i = 0; i < words.length; i++) { wordMap.put(words[i], i); } for (int i = 0; i < words.length; i++) { for (int j = 0; j < words[i].length(); j++) { List<Integer> indexes = null; String str1 = words[i].substring(0, j); String str2 = words[i].substring(j); if (isPalindrome(str1)) { String revWord2 = new StringBuilder(str2).reverse().toString(); if (wordMap.getOrDefault(revWord2, -1) >= 0 && wordMap.get(revWord2) != i) { indexes = new ArrayList<Integer>(); indexes.add(wordMap.get(revWord2)); indexes.add(i); results.add(indexes); } } if (str2.length() != 0 && isPalindrome(str2)) { String revWord1 = new StringBuilder(str1).reverse().toString(); if (wordMap.getOrDefault(revWord1, -1) >= 0 && wordMap.get(revWord1) != i && revWord1.length() != 0) { indexes = new ArrayList<Integer>(); indexes.add(i); indexes.add(wordMap.get(revWord1)); results.add(indexes); } } } } return results; } private boolean isPalindrome(String s) { int l = 0; int r = s.length() - 1; while (l < r) { if (s.charAt(l++) != s.charAt(r--)) { return false; } } return true; } public static void main(String[] args) { // TODO Auto-generated method stub String[] words = new String[] { "abcd", "dcba", "lls", "s", "sssll" }; PalindromicPair p = new PalindromicPair(); p.palindromePairs(words); } }
package com.test.accessmodifiers; /** * Created by srikanth on 23/12/16. */ public class DefaultClass { /* Default Public Private Protect */ int count = 100; String message = "Hello"; int getCount(){ return count; } void printMessage(){ System.out.println(message); } String getMessage(){ return message; } }
package littleservantmod.client.gui; import littleservantmod.api.IServant; import littleservantmod.api.profession.behavior.IBehavior; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.inventory.GuiContainer; public class ElementChangeBehaviorCurrent extends ElementChangeBehavior { protected IBehavior now; protected GuiButton buttonOk; public ElementChangeBehaviorCurrent(GuiContainer gui, int posX, int posY, IBehavior behavior, IServant servant, GuiButton buttonOk) { super(gui, posX, posY, behavior, servant); this.now = behavior; this.buttonOk = buttonOk; } public void setBehavior(IBehavior behavior) { this.behavior = behavior; this.buttonOk.enabled = !this.now.equals(this.behavior); } public IBehavior getBehavior() { return this.behavior; } }
package com.tencent.mm.plugin.appbrand.dynamic.widget; import android.util.Log; import com.tencent.mm.ipcinvoker.wx_extension.a.a; import com.tencent.mm.ipcinvoker.wx_extension.a.a.b; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.c; class c$1 implements Runnable { c$1() { } public final void run() { a aVar = b.dnp; c fJ = a.fJ("100284"); if (fJ == null) { x.i("MicroMsg.WidgetDrawableViewFactory", "widget canvas mode ABTest item is null."); } else if (fJ.isValid()) { try { c.ki(bi.getInt((String) fJ.ckq().get("mode"), 0)); x.i("MicroMsg.WidgetDrawableViewFactory", "current canvas mode is : %d", new Object[]{Integer.valueOf(c.bB())}); } catch (Throwable e) { x.w("MicroMsg.WidgetDrawableViewFactory", "parse widget canvas mode error : %s", new Object[]{Log.getStackTraceString(e)}); } } else { c.ki(0); } } }
package capitulo07; import java.security.SecureRandom; public class DeckOfCards { private Card[] deck; // array de objetos Card private int currentCard; private static final int NUMBER_OF_CARDS = 52; private static final SecureRandom randomNumbers = new SecureRandom(); public DeckOfCards() { String[] faces = { "As", "Dois", "Tres", "Quatro", "Cinco", "Seis", "Sete", "Oito", "Nove", "Dez", "Valete", "Dama", "Rei" }; String[] suits = { "Copas", "Ouros", "Paus", "Espadas" }; deck = new Card[NUMBER_OF_CARDS];// cria array de objetos Card currentCard = 0; // primeira carta distribuida // preenche baralho com objetos Card for (int count = 0; count < deck.length; count++) deck[count] = new Card(faces[count % 13], suits[count / 13]); } public void shuffle() { currentCard = 0; for (int first = 0; first < deck.length; first++) { int second = randomNumbers.nextInt(NUMBER_OF_CARDS); Card temp = deck[first]; deck[first] = deck[second]; deck[second] = temp; } } public void shuffleFisherYates() { currentCard = 0; for (int i = NUMBER_OF_CARDS; i <= deck.length; i--) { while (i-- > 0) { int j = (int) (Math.random() * (i + 1)); Card temp = deck[j]; deck[j] = deck[i]; deck[i] = temp; } } } public Card dealCard() { if (currentCard < deck.length) return deck[currentCard++]; else return null; } public void hasEven() { currentCard = 0; int evens = 0; String evenSuit = ""; String evenFace = ""; for (int i = 0; i < 5; i++) { Card temp = deck[i]; deck[i] = deck[i + 1]; if (temp.getSuit() == deck[i].getSuit()) { evens++; evenSuit = deck[i].getSuit(); } else if (temp.getFace() == deck[i].getFace()) { evens++; evenFace = deck[i].getFace(); } else { deck[i + 1] = temp; } } if (evenSuit != "") { System.out.printf("\nExiste(m) %d par(es) de: %s", evens, evenSuit); } if (evenFace != "") { System.out.printf("\nExiste(m) %d par(es) de: %s", evens, evenFace); } } }
package rent.api.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import rent.common.repository.UserRepository; import rent.common.entity.UserEntity; import java.util.ArrayList; import java.util.List; @Service public class CustomUserDetailsService implements UserDetailsService { private final UserRepository userRepository; @Autowired public CustomUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Transactional(readOnly = true) @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity userEntity = userRepository.findByLogin(username); if (userEntity == null) { String message = String.format("authentication failure username: '%s'", username); throw new UsernameNotFoundException(message); } List<GrantedAuthority> authorities = new ArrayList<>(1); authorities.add(new SimpleGrantedAuthority(userEntity.getRole().getName())); String password = userEntity.getPassword(); boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; boolean accountNonLocked = !userEntity.getBlocked(); return new User(userEntity.getLogin(), password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); } }
package com.fourstay.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.fourstay.utilities.Driver; public class SearchPage { public SearchPage() { PageFactory.initElements(Driver.getInstance(), this); } @FindBy(id = "iLocName") public WebElement schoolName; @FindBy(id = "rentoutfrom2") public WebElement startDate; @FindBy(id = "rentoutto2") public WebElement endDate; @FindBy(css="#search") public WebElement searchBtn; }
public class first { public static void main(String[] args){ //System.out.println("This is first file of java in GIT"); int n = 1000; int[] a = new int[n*n*n*n]; } }
package redis_test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * Description: * * @author Baltan * @date 2019/1/7 15:59 */ public class JedisPoolUtil { private static volatile JedisPool jedisPool; private JedisPoolUtil() { } public static JedisPool getInstance() { if (jedisPool == null) { synchronized (JedisPoolUtil.class) { if (jedisPool == null) { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(1000); poolConfig.setMaxIdle(32); poolConfig.setMaxWaitMillis(100 * 1000); poolConfig.setTestOnBorrow(true); jedisPool = new JedisPool(poolConfig, "127.0.0.1", 6379); } } } return jedisPool; } public static void release(Jedis jedis) { try { jedis.close(); } catch (Exception e) { if (jedis != null) { try { jedis.disconnect(); } catch (Exception e1) { } } } } }
import java.util.*; public class TheKWeakestRowsInAMatrix { public static int[] kWeakestRows(int[][] mat, int k) { int[] res = new int[k]; HashMap<Integer,Integer> map = new HashMap<>(); int num =0; for (int[] row : mat){ int add =0; for (int i =0;i< row.length;i++){ if (row[i]==1){ add++; } } map.put(num,add); num++; } List<Map.Entry<Integer, Integer> > list = new LinkedList<Map.Entry<Integer, Integer> >( map.entrySet()); // Sort the list using lambda expression Collections.sort( list, (i1, i2) -> i1.getValue().compareTo(i2.getValue())); // put data from sorted list to hashmap HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } Iterator iterator = temp.entrySet().iterator(); int checkK =0; while (iterator.hasNext() && checkK <k){ Map.Entry element = (Map.Entry) iterator.next(); res[checkK] = (int) element.getKey(); checkK++; } return res; } public static void main(String[] args) { int[][] mat = {{1,1,0,0,0},{1,1,1,1,0}, {1,0,0,0,0}, {1,1,0,0,0}, {1,1,1,1,1}}; int[] res = kWeakestRows(mat,3); for (int i =0;i< res.length;i++){ System.out.print(res[i]+ " "); } } }
package com.e6soft.bpm.service; import org.jdom.Element; import com.e6soft.bpm.model.FlownodeMsg; import com.e6soft.core.service.BaseService; /** * 节点消息配置 * @author 陈福忠 * */ public interface FlownodeMsgService extends BaseService<FlownodeMsg,String> { /** * 根据nodeId获取对应的消息配置 * @param nodeId * @return */ public FlownodeMsg singleByNodeId(String nodeId); /** * 导出所有节点消息配置 * @author 陈福忠 * @param nodeId * @return */ public Element exportFlowNodeMsgElement(String nodeId); /** * 导入所有消息配置 * @author 陈福忠 * @param nodeId * @param flownodeMsg */ public void importFlowNodeMsg(String nodeId, Element flownodeMsg); }
package com.serhii.cryptobook.project.service.impl; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; public class Des56ServiceCrypto extends DefaultServiceCrypto { private final static String ALGORYTHM = "DES/ECB/PKCS5Padding"; private Cipher cipher; public Des56ServiceCrypto() { try { this.cipher = Cipher.getInstance(ALGORYTHM); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { e.printStackTrace(); } } public byte[] encrypt(byte[] plainText, Key key) { byte[] cipherText = null; try { cipher.init(Cipher.ENCRYPT_MODE, key); cipherText = cipher.doFinal(plainText); } catch (InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) { e.printStackTrace(); } return cipherText; } public byte[] decrypt(byte[] cipherText, Key key) { byte[] plainText = null; try { cipher.init(Cipher.DECRYPT_MODE, key); plainText = cipher.doFinal(cipherText); } catch (InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) { e.printStackTrace(); } return plainText; } }
package ${package}.models; public class SampleModel { }
package androidx.databinding; public class DataBinderMapperImpl extends MergedDataBinderMapper { DataBinderMapperImpl() { addMapper(new tkhub.project.kesbewa.DataBinderMapperImpl()); } }
package Lab01.Zad4; public class Duck { FlyBehavior fly_behavior; QuackBehavior quack_behavior; public void setFlyBehavior (FlyBehavior fly) { fly_behavior = fly; } public void setQuackBehavior(QuackBehavior quack) { quack_behavior = quack; } public void performFly() { this.fly_behavior.fly(); } public void performQuack() { this.quack_behavior.quack(); } }
package io.ygg.common; import org.junit.Test; import static org.junit.Assert.assertNotNull; /** * Created by Miu on 11/01/2017. */ public class ConfigTest { @Test public void simpleConstructorTest() { Config config = new Config(); assertNotNull(config); } }
package gui; import online.FBPlayer; import online.OnlineGameService; import sound.MP3; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; /** * extends from ClassTetris * Created by cuong on 11/22/2015. */ public class OnlineTetris extends ClassicTetris { protected OnlineGameService onlineService; protected FBPlayer bestPlayer; protected FBPlayer currentPlayer; public final static String VICTORY = "./sound/Victory.mp3"; public OnlineTetris(JFrame pr, int width, int height) { super(pr, width, height); onlineService = new OnlineGameService(); bestPlayer = onlineService.getBestPlayer(); JOptionPane.showMessageDialog(this, "You need to login with Facebook"); currentPlayer = onlineService.getCurrentPlayer(); try { background = ImageIO.read(new File("./img/background1.jpg")); } catch (IOException e) { e.printStackTrace(); } System.out.println("Waiting, please....."); NIGHTMARE_MODE = true; } @Override public void stopGame() { currentPlayer.setScore(score); gameOn = false; timer.stop(); if (score <= bestPlayer.getScore()) { MP3.play(DEFEATED); } else { MP3.play(VICTORY); int choice; if (currentPlayer.getFbID() == bestPlayer.getFbID()) { choice = JOptionPane.showConfirmDialog(OnlineTetris.this, "You are legendary, " + currentPlayer.getName() + ".\n" + "You beated your previous best record. Do you wanna update it?", "Victory", JOptionPane.YES_NO_OPTION); } else { choice = JOptionPane.showConfirmDialog(OnlineTetris.this, "You beated the current top player\n" + "Do you wanna replace by yours in our honor board?", "Victory", JOptionPane.YES_NO_OPTION); } if (choice == JOptionPane.YES_OPTION) { onlineService.postBestPlayer(currentPlayer); } } /**can not use this feature because of being not permitted of Facebook*/ /*int choice = JOptionPane.showConfirmDialog(OnlineTetris.this, "Do you wanna share your record to your Facebook's wall?", "Share now...", JOptionPane.YES_NO_OPTION); if (choice == JOptionPane.YES_OPTION) { String post = currentPlayer.getName() + " has been just get " + currentPlayer.getScore() + " points in Nightmare mode with our Tetris game.\n" + "Do you wanna get high score with our awesome game??? ^_^\n" + "Join game free here: http://www.dailyheroes.ga/tetris/"; onlineService.publishPost(post); JOptionPane.showMessageDialog(this, "Share successfully ^^!"); }*/ } @Override public Container createControlPanel() { Font font = new Font("Tahoma", Font.BOLD, 30); Container rootPanel = new JPanel() { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.LIGHT_GRAY); g.setFont(font); g.draw3DRect(10, 0, 2, OnlineTetris.this.getHeight(), true); g.setColor(Color.red); g.drawString("Top Player", 40, 70); g.drawImage(bestPlayer.getPfPicture(), 70, 90, null); g.drawString(bestPlayer.getName(), 40, 230); g.drawString("Score: " + bestPlayer.getScore(), 40, 270); g.setColor(Color.LIGHT_GRAY); g.fill3DRect(10, 300, 350, 2, true); g.setColor(Color.BLUE); g.drawImage(currentPlayer.getPfPicture(), 70, 350, null); g.drawString(currentPlayer.getName(), 40, 490); g.setColor(Color.lightGray); g.drawString("Blocks: " + count, 40, 550); g.drawString("Score: " + score, 40, 600); g.drawImage(trademark, 25, OnlineTetris.this.getHeight()-35, null); } }; rootPanel.setPreferredSize(new Dimension(CONTROL_PANEL_WIDTH + 15, getHeight())); return rootPanel; } public static void startX(JFrame menuFrame) { mainFrame = new JFrame("Challenge Tetris - Online mode"); int width = 28, height = width - ClassicTetris.TOP_SPACE + 2; JComponent container = (JComponent)mainFrame.getContentPane(); container.setLayout(new BorderLayout()); OnlineTetris tetris = null; try { tetris = new OnlineTetris(menuFrame, width*OnlineTetris.PIXELS+2, height*OnlineTetris.PIXELS+2); } catch (IllegalArgumentException e) { JOptionPane.showMessageDialog(null, "You haven't completed login " + "with Facebook!", "Error", JOptionPane.ERROR_MESSAGE); mainFrame.dispose(); menuFrame.setVisible(true); return ; } container.add(tetris, BorderLayout.CENTER); Container panel = tetris.getControlPanel(); container.add(panel, BorderLayout.EAST); mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); mainFrame.pack(); tetris.requestFocus(); final OnlineTetris finalTetris = tetris; mainFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent arg0) { finalTetris.returnToMenu(); } }); mainFrame.setResizable(false); mainFrame.setLocationRelativeTo(null); mainFrame.setVisible(true); } }
package trees.citrus; import java.util.Comparator; import java.util.HashSet; import trees.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Citrus<K, V> implements Map<K, V> { private final Comparator<? super K> comparator; private final K min; private final Node<K, V> root; public Citrus(final K min, final K max) { this.min = min; this.root = new Node<K, V>(max,null); this.comparator = null; } public Citrus(final K min, final K max, final Comparator<? super K> comparator) { this.min = min; this.root = new Node<K, V>(max,null); this.comparator = comparator; } /** * Given some object, returns an appropriate {@link Comparable} object. * If the comparator was initialized upon creating the tree, the * {@link Comparable} object uses it; otherwise, assume that the given * object implements {@link Comparable}. * * @param object The object * @return The appropriate {@link Comparable} object */ @SuppressWarnings("unchecked") private Comparable<? super K> comparable(final Object object) { if (object == null) throw new NullPointerException(); if (comparator == null) return (Comparable<? super K>)object; return new Comparable<K>() { final Comparator<? super K> compar = comparator; final K obj = (K) object; public int compareTo(final K other) { return compar.compare(obj, other); } }; } public boolean validate(){ return doValidate(this.root.left, this.min , this.root.key); } boolean doValidate(Node<K, V> node, K min, K max){ if (node == null) return true; final Comparable<? super K> k = comparable(node.key); if ( k.compareTo(max) >=0 || k.compareTo(min) <= 0 ) return false; return doValidate(node.left,min,node.key) && doValidate(node.right,node.key,max); } public V get(K key){ final Comparable<? super K> k = comparable(key); RCU.rcuReadLock(); Node<K, V> curr = this.root; while(curr!=null){ int res = k.compareTo(curr.key); if(res == 0) break; if(res > 0){ //key > x.key curr=curr.right; }else{ curr=curr.left; } } RCU.rcuReadUnlock(); if(curr!=null){ return curr.value; } return null; } private boolean citrusValidate(Node<K,V> prev,int tag ,Node<K,V> curr, boolean isLeft){ boolean result; if (curr==null){ if(isLeft){ result = (!(prev.marked) && (prev.left==curr) && (prev.tagLeft==tag)); }else{ result = (!(prev.marked) && (prev.right==curr) && (prev.tagRight==tag)); } } else { if(isLeft){ result = (!(prev.marked) && !(curr.marked) && prev.left==curr); }else{ result = (!(prev.marked) && !(curr.marked) && prev.right==curr); } } return result; } public V put(K key, V val){ final Comparable<? super K> k = comparable(key); V oldValue = null; while(true) { RCU.rcuReadLock(); Node<K, V> prev = null; Node<K, V> curr = this.root; int res = -1; while(curr!=null){ prev=curr; res = k.compareTo(curr.key); if(res == 0) { //oldValue = curr.value; break; } if(res > 0){ //key > x.key curr=curr.right; }else{ curr=curr.left; } } int tag = res < 0? prev.tagLeft : prev.tagRight; RCU.rcuReadUnlock(); if(res == 0) { curr.lock.lock(); if(!curr.marked){ oldValue = curr.value; curr.value = val; curr.lock.unlock(); return oldValue; } curr.lock.unlock(); continue; } prev.lock.lock(); if(citrusValidate(prev, tag ,curr, res < 0)){ Node<K, V> node = new Node<K, V>(key,val); assert(curr==null); if (res > 0 ) { prev.right = node; } else { prev.left = node; } prev.lock.unlock(); return oldValue; } prev.lock.unlock(); } } public V remove(K key){ final Comparable<? super K> k = comparable(key); while(true){ RCU.rcuReadLock(); Node<K, V> prev = null; Node<K, V> curr = this.root; V oldValue = null; int res = -1; boolean isLeft = true; while(curr!=null){ res = k.compareTo(curr.key); if(res == 0) { //oldValue = curr.value; break; } prev=curr; if(res > 0){ //key > x.key curr=curr.right; isLeft = false; }else{ curr=curr.left; isLeft = true; } } RCU.rcuReadUnlock(); if(res!= 0) { return oldValue; } prev.lock.lock(); curr.lock.lock(); assert(curr!=null); oldValue = curr.value; if(!citrusValidate(prev,0,curr,isLeft)){ prev.lock.unlock(); curr.lock.unlock(); continue; } if (curr.left == null){ //no left child curr.marked = true; if(isLeft){ prev.left = curr.right; if(prev.left == null){ prev.tagLeft++; } }else { prev.right= curr.right; if(prev.right == null){ prev.tagRight++; } } prev.lock.unlock(); curr.lock.unlock(); return oldValue; } if (curr.right == null){ //no right child curr.marked = true; if(isLeft){ prev.left = curr.left; if(prev.left == null){ prev.tagLeft++; } }else { prev.right = curr.left; if(prev.right == null){ prev.tagRight++; } } prev.lock.unlock(); curr.lock.unlock(); return oldValue; } //both children Node<K, V> prevSucc = curr; Node<K, V> succ = curr.right; Node<K, V> succL = succ.left; while(succL != null){ prevSucc = succ; succ = succL; succL = succ.left; } boolean isSuccLeft = true; if (prevSucc == curr){ isSuccLeft = false; } prevSucc.lock.lock(); succ.lock.lock(); if(!(citrusValidate(prevSucc,0,succ,isSuccLeft) && citrusValidate(succ,succ.tagLeft,null,true))){ prevSucc.lock.unlock(); succ.lock.unlock(); prev.lock.unlock(); curr.lock.unlock(); continue; } curr.marked = true; Node<K,V> node = new Node<K,V>(succ.key,succ.value); node.left = curr.left; node.right = curr.right; node.lock.lock(); if (isLeft){ prev.left = node; } else{ prev.right = node; } RCU.synchronize(); succ.marked = true; if (prevSucc == curr){ node.right = succ.right; if(node.right == null){ node.tagRight++; } } else{ prevSucc.left=succ.right; if(prevSucc.left == null){ prevSucc.tagLeft++; } } prevSucc.lock.unlock(); succ.lock.unlock(); prev.lock.unlock(); curr.lock.unlock(); node.lock.unlock(); return oldValue; } } @Override public HashSet<K> getAllKeys() { HashSet<K> keys = new HashSet<K>(); getAllKeysImpl(this.root.left,keys); return keys; } private void getAllKeysImpl(Node<K, V> node, HashSet<K> keys) { if(node!=null){ keys.add(node.key); getAllKeysImpl(node.left, keys); getAllKeysImpl(node.right, keys); } } private static class Node<K, V>{ public Node(K key, V value) { this.key = key; this.value = value; this.left = null; this.right = null; this.marked = false; this.tagLeft = 0; this.tagRight = 0; this.lock = new ReentrantLock(); } final K key; V value; Node<K, V> left; Node<K, V> right; boolean marked; int tagLeft; int tagRight; Lock lock; } }
package commands; import app.Application; public class AddShop implements Command{ @Override public String getCommand() { return "ДОБАВИТЬ_МАГАЗИН"; } @Override public void parceCommand(String command, Application application) { application.addShop(command); } }
package com.tyss.capgemini.loanproject.services; import com.tyss.capgemini.loanproject.exceptions.FormReviewChoiceException; import com.tyss.capgemini.loanproject.factory.FactoryClass; import com.tyss.capgemini.loanproject.validation.ValidationClass; public class LadServicesImplementation implements LadServicesDeclaration{ ValidationClass validationClass = new ValidationClass(); /** * @return true if all the loan programs are viewed, false o */ @Override public boolean viewLoanPrograms() { if (FactoryClass.getLadDao().viewLoanPrograms()) { return true; } else return false; } /** * @param String appId, String status * @return true if status is changed to approved or rejected, false otherwise */ @Override public boolean ladReviewForms(String apid, String status) { if ((status.equalsIgnoreCase("approved")) || (status.equalsIgnoreCase("rejected"))) { FactoryClass.getLadDao().ladReviewForms(apid, status); return true; } else throw new FormReviewChoiceException("please write only approved or rejected."); } /** * @param String planString * @return true if the application forms are shown to the LAD, false otherwise */ @Override public boolean ladViewForms(String planString) { if (FactoryClass.getLadDao().ladViewForms(planString)) { return true; } else return false; } /** * @return true if all the requested forms are displayed */ @Override public boolean requestedForms() { if (FactoryClass.getLadDao().requestedForms() == true) { return true; } else return false; } /** * @return true if all the loans are displayed */ @Override public boolean loanTypes() { return FactoryClass.getLadDao().loanTypes(); } @Override public String loanTypes(String k) { return FactoryClass.getLadDao().loanTypes(k); } @Override public boolean applicationExist(String id) { return FactoryClass.getLadDao().applicationExist(id); } }
public class Employee { private String name; private String iD; private String hireDate; public Employee(String n, String i, String hire) { name = n; iD = i; hireDate = hire; } public String getName() {return name;} public void setName(String name) {this.name = name;} public String getiD() {return iD;} public void setiD(String iD) {this.iD = iD;} public String getHireDate() {return hireDate;} public void setHireDate(String hireDate) {this.hireDate = hireDate;} private boolean validEmpNum(String emp) { boolean stat = true; if(emp.length() != 5) { stat = false; } else { // if(!Ch) } return stat; } }
package com.mySampleApplication.server.services; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.mySampleApplication.client.services.CustomerTypeService; import com.mySampleApplication.shared.model.CustomerTypeData; import java.util.ArrayList; import java.util.List; /** * @author zhouguixing * @date 2019/4/27 4:34 * @description */ public class CustomerTypeServiceImpl extends RemoteServiceServlet implements CustomerTypeService { private com.zgx.bootdemo.service.CustomerTypeService serivce = HttpInvokerProxyUtil.getInstance().doRefer(com.zgx.bootdemo.service.CustomerTypeService.class, this.url); @Override public List<CustomerTypeData> list() { List<com.zgx.bootdemo.entity.CustomerType> list = serivce.list(); List<CustomerTypeData> list1 = new ArrayList<>(); for (com.zgx.bootdemo.entity.CustomerType customerType : list) { CustomerTypeData customerTypeData1 = new CustomerTypeData(); CglibBeanCopierUtil.copyProperties(customerType, customerTypeData1); list1.add(customerTypeData1); } return list1; } }
package com.lolRiver.river.persistence.interfaces; import com.lolRiver.river.models.State; import com.lolRiver.river.models.Video; import java.util.List; /** * @author mxia (mxia@lolRiver.com) * 9/30/13 */ public interface VideoDao { // get the Video with given id public Video getVideoFromId(final int id); public List<Video> getUncovertedVideos(); // create an Video. Returns created Video, or null if not possible public Video insertVideo(Video video); // update an Video with given id to given state. Returns true if successful. public boolean updateVideoState(int id, State state); }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.dao; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.StringTokenizer; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.openkm.bean.Document; import com.openkm.bean.ExtendedAttributes; import com.openkm.bean.Folder; import com.openkm.bean.Mail; import com.openkm.bean.Permission; import com.openkm.core.AccessDeniedException; import com.openkm.core.Config; import com.openkm.core.DatabaseException; import com.openkm.core.ItemExistsException; import com.openkm.core.PathNotFoundException; import com.openkm.core.RepositoryException; import com.openkm.dao.bean.NodeBase; import com.openkm.dao.bean.NodeDocument; import com.openkm.dao.bean.NodeFolder; import com.openkm.dao.bean.NodeMail; import com.openkm.dao.bean.NodeNote; import com.openkm.dao.bean.NodeProperty; import com.openkm.dao.bean.RegisteredPropertyGroup; import com.openkm.module.db.base.BaseNoteModule; import com.openkm.module.db.stuff.SecurityHelper; import com.openkm.util.CloneUtils; import com.openkm.util.FormatUtil; import com.openkm.util.PathUtils; public class NodeBaseDAO { private static Logger log = LoggerFactory.getLogger(NodeBaseDAO.class); private static NodeBaseDAO single = new NodeBaseDAO(); private NodeBaseDAO() { } public static NodeBaseDAO getInstance() { return single; } /** * Find by pk */ public NodeBase findByPk(String uuid) throws PathNotFoundException, DatabaseException { log.debug("findByPk({})", uuid); Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); NodeBase nBase = (NodeBase) session.get(NodeBase.class, uuid); if (nBase == null) { throw new PathNotFoundException(uuid); } // Security Check SecurityHelper.checkRead(nBase); initialize(nBase); log.debug("findByPk: {}", nBase); return nBase; } catch (HibernateException e) { throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get node path from UUID */ public String getPathFromUuid(String uuid) throws PathNotFoundException, DatabaseException { return calculatePathFromUuid(uuid); } /** * Get node path from UUID */ public String getPathFromUuid(Session session, String uuid) throws PathNotFoundException, HibernateException { return calculatePathFromUuid(session, uuid); } /** * Get node UUID from path */ public String getUuidFromPath(String path) throws PathNotFoundException, DatabaseException { return calculateUuidFromPath(path); } /** * Get node UUID from path */ public String getUuidFromPath(Session session, String path) throws PathNotFoundException, DatabaseException { return calculateUuidFromPath(session, path); } /** * Check for item existence. */ public boolean itemPathExists(String path) throws DatabaseException { try { getUuidFromPath(path); return true; } catch (PathNotFoundException e) { return false; } } /** * Check for item existence. */ public boolean itemUuidExists(String uuid) throws DatabaseException { Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); NodeBase nBase = (NodeBase) session.get(NodeBase.class, uuid); if (nBase == null) { return false; } // Security Check SecurityHelper.checkRead(nBase); return true; } catch (HibernateException e) { throw new DatabaseException(e.getMessage(), e); } catch (PathNotFoundException e) { return false; } finally { HibernateUtil.close(session); } } /** * Get node path from UUID. This is the old one which calculates the path. */ private String calculatePathFromUuid(String uuid) throws PathNotFoundException, DatabaseException { log.debug("calculatePathFromUuid({})", uuid); Session session = null; if (Config.ROOT_NODE_UUID.equals(uuid)) { return "/"; } try { session = HibernateUtil.getSessionFactory().openSession(); String path = getPathFromUuid(session, uuid); log.debug("calculatePathFromUuid: {}", path); return path; } catch (HibernateException e) { throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get node path from UUID. This is the old one which calculates the path. */ private String calculatePathFromUuid(Session session, String uuid) throws PathNotFoundException, HibernateException { log.debug("calculatePathFromUuid({}, {})", session, uuid); String childUuid = null; String path = ""; do { NodeBase node = (NodeBase) session.get(NodeBase.class, uuid); if (node == null) { throw new PathNotFoundException(uuid); } else { path = "/".concat(node.getName()).concat(path); childUuid = uuid; uuid = node.getParent(); if (uuid.equals(childUuid)) { log.warn("*** Node is its own parent: {} -> {} ***", uuid, path); break; } } } while (!Config.ROOT_NODE_UUID.equals(uuid)); log.debug("calculatePathFromUuid: {}", path); return path; } /** * Get node UUID from path. This is the old one which calculates the uuid. */ private String calculateUuidFromPath(String path) throws PathNotFoundException, DatabaseException { log.debug("calculateUuidFromPath({})", path); Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); String uuid = calculateUuidFromPath(session, path); log.debug("calculateUuidFromPath: {}", uuid); return uuid; } catch (HibernateException e) { throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get node UUID from path. This is the old one which calculates the uuid. */ private String calculateUuidFromPath(Session session, String path) throws PathNotFoundException, HibernateException { log.debug("calculateUuidFromPath({}, {})", session, path); String qs = "select nb.uuid from NodeBase nb where nb.parent=:parent and nb.name=:name"; Query q = session.createQuery(qs); String uuid = Config.ROOT_NODE_UUID; String name = ""; // Fix for & and &amp; strings in the path path = PathUtils.encodeEntities(path); for (StringTokenizer st = new StringTokenizer(path, "/"); st.hasMoreTokens();) { name = st.nextToken(); q.setString("name", name); q.setString("parent", uuid); uuid = (String) q.setMaxResults(1).uniqueResult(); if (uuid == null) { throw new PathNotFoundException(path); } } log.debug("calculateUuidFromPath: {}", uuid); return uuid; } /** * Get node path from UUID */ @SuppressWarnings("unused") private String searchPathFromUuid(String uuid) throws PathNotFoundException, DatabaseException { log.debug("searchPathFromUuid({})", uuid); Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); String path = getPathFromUuid(session, uuid); if (path == null) { throw new PathNotFoundException(uuid); } log.debug("searchPathFromUuid: {}", path); return path; } catch (HibernateException e) { throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get node path from UUID */ @SuppressWarnings("unused") private String searchPathFromUuid(Session session, String uuid) throws PathNotFoundException, HibernateException { log.debug("searchPathFromUuid({})", uuid); String qs = "select nb.path from NodeBase nb where nb.uuid=:uuid"; Query q = session.createQuery(qs); q.setString("uuid", uuid); String path = (String) q.setMaxResults(1).uniqueResult(); log.debug("searchPathFromUuid: {}", path); return path; } /** * Get node UUID from path. This is the old one which calculates the uuid. */ @SuppressWarnings("unused") private String searchUuidFromPath(String path) throws PathNotFoundException, DatabaseException { log.debug("searchUuidFromPath({})", path); String qs = "select nb.uuid from NodeBase nb where nb.path=:path"; Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); Query q = session.createQuery(qs); q.setString("path", path); String uuid = (String) q.setMaxResults(1).uniqueResult(); if (uuid == null) { throw new PathNotFoundException(path); } log.debug("searchUuidFromPath: {}", uuid); return uuid; } catch (HibernateException e) { throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get user permissions */ public Map<String, Integer> getUserPermissions(String uuid) throws PathNotFoundException, DatabaseException { log.debug("getUserPermissions({})", uuid); Map<String, Integer> ret = new HashMap<String, Integer>(); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); if (node != null) { Hibernate.initialize(ret = node.getUserPermissions()); } HibernateUtil.commit(tx); log.debug("getUserPermissions: {}", ret); return ret; } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Grant user permissions */ public void grantUserPermissions(String uuid, String user, int permissions, boolean recursive) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.debug("grantUserPermissions({})", uuid); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Root node NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); if (recursive) { long begin = System.currentTimeMillis(); int total = grantUserPermissionsInDepth(session, node, user, permissions); log.trace("grantUserPermissions.Total: {}", total); log.info("grantUserPermissions.Time: {}", FormatUtil.formatMiliSeconds(System.currentTimeMillis() - begin)); } else { grantUserPermissions(session, node, user, permissions, false); } HibernateUtil.commit(tx); log.debug("grantUserPermissions: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Grant user permissions */ private int grantUserPermissions(Session session, NodeBase node, String user, int permissions, boolean recursive) throws PathNotFoundException, AccessDeniedException, DatabaseException, HibernateException { // log.info("grantUserPermissions({})", node.getUuid()); boolean canModify = true; // Security Check if (recursive) { canModify = SecurityHelper.isGranted(node, Permission.READ) && SecurityHelper.isGranted(node, Permission.SECURITY); } else { SecurityHelper.checkRead(node); SecurityHelper.checkSecurity(node); } if (canModify) { Integer currentPermissions = node.getUserPermissions().get(user); if (currentPermissions == null) { node.getUserPermissions().put(user, permissions); } else { node.getUserPermissions().put(user, permissions | currentPermissions); } session.update(node); return 1; } else { return 0; } } /** * Grant recursively */ @SuppressWarnings("unchecked") private int grantUserPermissionsInDepth(Session session, NodeBase node, String user, int permissions) throws PathNotFoundException, AccessDeniedException, DatabaseException, HibernateException { int total = grantUserPermissions(session, node, user, permissions, true); // Calculate children nodes String qs = "from NodeBase nb where nb.parent=:parent"; Query q = session.createQuery(qs); q.setString("parent", node.getUuid()); List<NodeBase> ret = q.list(); // Security Check SecurityHelper.pruneNodeList(ret); for (NodeBase child : ret) { total += grantUserPermissionsInDepth(session, child, user, permissions); } return total; } /** * Revoke user permissions */ public void revokeUserPermissions(String uuid, String user, int permissions, boolean recursive) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.debug("revokeUserPermissions({})", uuid); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Root node NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); if (recursive) { long begin = System.currentTimeMillis(); int total = revokeUserPermissionsInDepth(session, node, user, permissions); log.trace("revokeUserPermissions.Time: {}", FormatUtil.formatMiliSeconds(System.currentTimeMillis() - begin)); log.info("revokeUserPermissions.Total: {}", total); } else { revokeUserPermissions(session, node, user, permissions, false); } HibernateUtil.commit(tx); log.debug("revokeUserPermissions: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Revoke user permissions */ private int revokeUserPermissions(Session session, NodeBase node, String user, int permissions, boolean recursive) throws PathNotFoundException, AccessDeniedException, DatabaseException, HibernateException { // log.info("revokeUserPermissions({})", node.getUuid()); boolean canModify = true; // Security Check if (recursive) { canModify = SecurityHelper.isGranted(node, Permission.READ) && SecurityHelper.isGranted(node, Permission.SECURITY); } else { SecurityHelper.checkRead(node); SecurityHelper.checkSecurity(node); } if (canModify) { Integer currentPermissions = node.getUserPermissions().get(user); if (currentPermissions != null) { Integer perms = ~permissions & currentPermissions; if (perms == Permission.NONE) { node.getUserPermissions().remove(user); } else { node.getUserPermissions().put(user, perms); } } session.update(node); return 1; } else { return 0; } } /** * Revoke recursively */ @SuppressWarnings("unchecked") private int revokeUserPermissionsInDepth(Session session, NodeBase node, String user, int permissions) throws PathNotFoundException, AccessDeniedException, DatabaseException, HibernateException { int total = revokeUserPermissions(session, node, user, permissions, true); // Calculate children nodes String qs = "from NodeBase nb where nb.parent=:parent"; Query q = session.createQuery(qs); q.setString("parent", node.getUuid()); List<NodeBase> ret = q.list(); // Security Check SecurityHelper.pruneNodeList(ret); for (NodeBase child : ret) { total += revokeUserPermissionsInDepth(session, child, user, permissions); } return total; } /** * Get role permissions */ public Map<String, Integer> getRolePermissions(String uuid) throws PathNotFoundException, DatabaseException { log.debug("getRolePermissions({})", uuid); Map<String, Integer> ret = new HashMap<String, Integer>(); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); if (node != null) { Hibernate.initialize(ret = node.getRolePermissions()); } HibernateUtil.commit(tx); log.debug("getRolePermissions: {}", ret); return ret; } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Grant role permissions */ public void grantRolePermissions(String uuid, String role, int permissions, boolean recursive) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.debug("grantRolePermissions({}, {}, {}, {})", new Object[] { uuid, role, permissions, recursive }); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Root node NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); if (recursive) { long begin = System.currentTimeMillis(); int total = grantRolePermissionsInDepth(session, node, role, permissions); log.trace("grantRolePermissions.Time: {}", FormatUtil.formatMiliSeconds(System.currentTimeMillis() - begin)); log.info("grantRolePermissions.Total: {}", total); } else { grantRolePermissions(session, node, role, permissions, false); } HibernateUtil.commit(tx); log.debug("grantRolePermissions: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Grant role permissions */ private int grantRolePermissions(Session session, NodeBase node, String role, int permissions, boolean recursive) throws PathNotFoundException, AccessDeniedException, DatabaseException, HibernateException { // log.info("grantRolePermissions({})", node.getUuid()); boolean canModify = true; // Security Check if (recursive) { canModify = SecurityHelper.isGranted(node, Permission.READ) && SecurityHelper.isGranted(node, Permission.SECURITY); } else { SecurityHelper.checkRead(node); SecurityHelper.checkSecurity(node); } if (canModify) { Integer currentPermissions = node.getRolePermissions().get(role); if (currentPermissions == null) { node.getRolePermissions().put(role, permissions); } else { node.getRolePermissions().put(role, permissions | currentPermissions); } session.update(node); return 1; } else { return 0; } } /** * Grant recursively */ @SuppressWarnings("unchecked") private int grantRolePermissionsInDepth(Session session, NodeBase node, String role, int permissions) throws PathNotFoundException, AccessDeniedException, DatabaseException, HibernateException { int total = grantRolePermissions(session, node, role, permissions, true); // Calculate children nodes String qs = "from NodeBase nb where nb.parent=:parent"; Query q = session.createQuery(qs); q.setString("parent", node.getUuid()); List<NodeBase> ret = q.list(); // Security Check SecurityHelper.pruneNodeList(ret); for (NodeBase child : ret) { total += grantRolePermissionsInDepth(session, child, role, permissions); } return total; } /** * Revoke role permissions */ public void revokeRolePermissions(String uuid, String role, int permissions, boolean recursive) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.debug("revokeRolePermissions({}, {}, {}, {})", new Object[] { uuid, role, permissions, recursive }); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Root node NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); if (recursive) { long begin = System.currentTimeMillis(); int total = revokeRolePermissionsInDepth(session, node, role, permissions); log.trace("revokeRolePermissions.Time: {}", FormatUtil.formatMiliSeconds(System.currentTimeMillis() - begin)); log.info("revokeRolePermissions.Total: {}", total); } else { revokeRolePermissions(session, node, role, permissions, false); } HibernateUtil.commit(tx); log.debug("revokeRolePermissions: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Revoke role permissions */ private int revokeRolePermissions(Session session, NodeBase node, String role, int permissions, boolean recursive) throws PathNotFoundException, AccessDeniedException, DatabaseException, HibernateException { // log.info("revokeRolePermissions({})", node.getUuid()); boolean canModify = true; // Security Check if (recursive) { canModify = SecurityHelper.isGranted(node, Permission.READ) && SecurityHelper.isGranted(node, Permission.SECURITY); } else { SecurityHelper.checkRead(node); SecurityHelper.checkSecurity(node); } if (canModify) { Integer currentPermissions = node.getRolePermissions().get(role); if (currentPermissions != null) { Integer perms = ~permissions & currentPermissions; if (perms == Permission.NONE) { node.getRolePermissions().remove(role); } else { node.getRolePermissions().put(role, perms); } } session.update(node); return 1; } else { return 0; } } /** * Revoke recursively */ @SuppressWarnings("unchecked") private int revokeRolePermissionsInDepth(Session session, NodeBase node, String role, int permissions) throws PathNotFoundException, AccessDeniedException, DatabaseException, HibernateException { int total = revokeRolePermissions(session, node, role, permissions, true); // Calculate children nodes String qs = "from NodeBase nb where nb.parent=:parent"; Query q = session.createQuery(qs); q.setString("parent", node.getUuid()); List<NodeBase> ret = q.list(); // Security Check SecurityHelper.pruneNodeList(ret); for (NodeBase child : ret) { total += revokeRolePermissionsInDepth(session, child, role, permissions); } return total; } /** * Change security of multiples nodes */ public void changeSecurity(String uuid, Map<String, Integer> grantUsers, Map<String, Integer> revokeUsers, Map<String, Integer> grantRoles, Map<String, Integer> revokeRoles, boolean recursive) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.debug("changeSecurity({}, {}, {}, {})", new Object[] { uuid, grantUsers, revokeUsers, grantRoles, revokeRoles, recursive }); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Root node NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); if (recursive) { long begin = System.currentTimeMillis(); int total = changeSecurityInDepth(session, node, grantUsers, revokeUsers, grantRoles, revokeRoles); log.trace("changeSecurity.Time: {}", FormatUtil.formatMiliSeconds(System.currentTimeMillis() - begin)); log.info("changeSecurity.Total: {}", total); } else { changeSecurity(session, node, grantUsers, revokeUsers, grantRoles, revokeRoles, false); } HibernateUtil.commit(tx); log.debug("grantRolePermissions: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Change security. * * @see com.openkm.util.pendtask.ChangeSecurityTask */ public int changeSecurity(Session session, NodeBase node, Map<String, Integer> grantUsers, Map<String, Integer> revokeUsers, Map<String, Integer> grantRoles, Map<String, Integer> revokeRoles, boolean recursive) throws PathNotFoundException, AccessDeniedException, DatabaseException, HibernateException { log.debug("changeSecurity({}, {}, {}, {}, {})", new Object[] { node.getUuid(), grantUsers, revokeUsers, grantRoles, revokeRoles }); boolean canModify = true; // Security Check if (recursive) { canModify = SecurityHelper.isGranted(node, Permission.READ) && SecurityHelper.isGranted(node, Permission.SECURITY); } else { SecurityHelper.checkRead(node); SecurityHelper.checkSecurity(node); } if (canModify) { // Grant Users for (Entry<String, Integer> userGrant : grantUsers.entrySet()) { Integer currentPermissions = node.getUserPermissions().get(userGrant.getKey()); if (currentPermissions == null) { node.getUserPermissions().put(userGrant.getKey(), userGrant.getValue()); } else { node.getUserPermissions().put(userGrant.getKey(), userGrant.getValue() | currentPermissions); } } // Revoke Users for (Entry<String, Integer> userRevoke : revokeUsers.entrySet()) { Integer currentPermissions = node.getUserPermissions().get(userRevoke.getKey()); if (currentPermissions != null) { Integer newPermissions = ~userRevoke.getValue() & currentPermissions; if (newPermissions == Permission.NONE) { node.getUserPermissions().remove(userRevoke.getKey()); } else { node.getUserPermissions().put(userRevoke.getKey(), newPermissions); } } } // Grant Roles for (Entry<String, Integer> roleGrant : grantRoles.entrySet()) { Integer currentPermissions = node.getRolePermissions().get(roleGrant.getKey()); if (currentPermissions == null) { node.getRolePermissions().put(roleGrant.getKey(), roleGrant.getValue()); } else { node.getRolePermissions().put(roleGrant.getKey(), roleGrant.getValue() | currentPermissions); } } // Revoke Roles for (Entry<String, Integer> roleRevoke : revokeRoles.entrySet()) { Integer currentPermissions = node.getRolePermissions().get(roleRevoke.getKey()); if (currentPermissions != null) { Integer newPermissions = ~roleRevoke.getValue() & currentPermissions; if (newPermissions == Permission.NONE) { node.getRolePermissions().remove(roleRevoke.getKey()); } else { node.getRolePermissions().put(roleRevoke.getKey(), newPermissions); } } } session.update(node); return 1; } else { return 0; } } /** * Change security recursively * * @see com.openkm.dao.PendingTaskDAO.processChangeSecurity(Session, NodeBase) */ @SuppressWarnings("unchecked") public int changeSecurityInDepth(Session session, NodeBase node, Map<String, Integer> grantUsers, Map<String, Integer> revokeUsers, Map<String, Integer> grantRoles, Map<String, Integer> revokeRoles) throws PathNotFoundException, AccessDeniedException, DatabaseException, HibernateException { int total = changeSecurity(session, node, grantUsers, revokeUsers, grantRoles, revokeRoles, true); // Calculate children nodes String qs = "from NodeBase nb where nb.parent=:parent"; Query q = session.createQuery(qs); q.setString("parent", node.getUuid()); List<NodeBase> ret = q.list(); // Security Check SecurityHelper.pruneNodeList(ret); for (NodeBase child : ret) { total += changeSecurityInDepth(session, child, grantUsers, revokeUsers, grantRoles, revokeRoles); } return total; } /** * Add category to node */ public void addCategory(String uuid, String catUuid) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.debug("addCategory({}, {})", uuid, catUuid); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); SecurityHelper.checkWrite(node); if (!node.getCategories().contains(catUuid)) { node.getCategories().add(catUuid); } session.update(node); HibernateUtil.commit(tx); log.debug("addCategory: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Remove category from node */ public void removeCategory(String uuid, String catUuid) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.debug("removeCategory({}, {})", uuid, catUuid); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); SecurityHelper.checkWrite(node); node.getCategories().remove(catUuid); session.update(node); HibernateUtil.commit(tx); log.debug("removeCategory: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Test for category in a node */ public boolean hasCategory(String uuid, String catId) throws PathNotFoundException, DatabaseException { log.debug("hasCategory({}, {})", uuid, catId); Session session = null; Transaction tx = null; boolean check; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); check = node.getCategories().contains(catId); HibernateUtil.commit(tx); log.debug("hasCategory: {}", check); return check; } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Test for category in use */ public boolean isCategoryInUse(String catUuid) throws DatabaseException { log.debug("isCategoryInUse({}, {})", catUuid); final String qs = "from NodeBase nb where :category in elements(nb.categories)"; final String sql = "select NCT_NODE from OKM_NODE_CATEGORY where NCT_CATEGORY = :catUuid"; Session session = null; Transaction tx = null; boolean check; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); Query q = session.createQuery(qs); q.setString("category", catUuid); check = !q.list().isEmpty(); HibernateUtil.commit(tx); log.debug("isCategoryInUse: {}", check); return check; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Add keyword to node */ public void addKeyword(String uuid, String keyword) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.debug("addKeyword({}, {})", uuid, keyword); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); SecurityHelper.checkWrite(node); if (!node.getKeywords().contains(keyword)) { node.getKeywords().add(keyword); } session.update(node); HibernateUtil.commit(tx); log.debug("addKeyword: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Remove keyword from node */ public void removeKeyword(String uuid, String keyword) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.debug("removeCategory({}, {})", uuid, keyword); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); SecurityHelper.checkWrite(node); node.getKeywords().remove(keyword); session.update(node); HibernateUtil.commit(tx); log.debug("removeCategory: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Test for category in a node */ public boolean hasKeyword(String uuid, String keyword) throws PathNotFoundException, DatabaseException { log.debug("hasKeyword({}, {})", uuid, keyword); Session session = null; Transaction tx = null; boolean check; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); check = node.getKeywords().contains(keyword); HibernateUtil.commit(tx); log.debug("hasKeyword: {}", check); return check; } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Subscribe user to node */ public void subscribe(String uuid, String user) throws PathNotFoundException, DatabaseException { log.debug("subscribe({}, {})", uuid, user); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); if (!node.getSubscriptors().contains(user)) { node.getSubscriptors().add(user); } session.update(node); HibernateUtil.commit(tx); log.debug("subscribe: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Remove user subscription */ public void unsubscribe(String uuid, String user) throws PathNotFoundException, DatabaseException { log.debug("unsubscribe({}, {})", uuid, user); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); node.getSubscriptors().remove(user); session.update(node); HibernateUtil.commit(tx); log.debug("unsubscribe: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get node subscriptors */ public Set<String> getSubscriptors(String uuid) throws PathNotFoundException, DatabaseException { log.debug("getSubscriptors({})", uuid); Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); Set<String> subscriptors = node.getSubscriptors(); Hibernate.initialize(subscriptors); log.debug("getSubscriptors: {}", subscriptors); return subscriptors; } catch (PathNotFoundException e) { throw e; } catch (HibernateException e) { throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Set node script */ public void setScript(String uuid, String code) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.debug("setScript({}, {})", uuid, code); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); SecurityHelper.checkWrite(node); node.setScripting(true); node.setScriptCode(code); session.update(node); HibernateUtil.commit(tx); log.debug("setScript: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Remove node script */ public void removeScript(String uuid) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.debug("removeScript({}, {})", uuid); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); SecurityHelper.checkWrite(node); node.setScripting(false); node.setScriptCode(null); session.update(node); HibernateUtil.commit(tx); log.debug("removeScript: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Obtain script code */ public String getScript(String uuid) throws PathNotFoundException, DatabaseException { log.debug("setScript({}, {})", uuid); Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); String code = node.getScriptCode(); log.debug("setScript: {}", code); return code; } catch (PathNotFoundException e) { throw e; } catch (HibernateException e) { throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get parent node uuid */ public String getParentUuid(String uuid) throws DatabaseException { log.debug("getParentUuid({})", uuid); String qs = "select nb.parent from NodeBase nb where nb.uuid=:uuid"; Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); Query q = session.createQuery(qs); q.setString("uuid", uuid); String parent = (String) q.setMaxResults(1).uniqueResult(); log.debug("getParentUuid: {}", parent); return parent; } catch (HibernateException e) { throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get parent node */ public NodeBase getParentNode(String uuid) throws DatabaseException { log.debug("getParentNode({})", uuid); Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); NodeBase parentNode = getParentNode(session, uuid); initializeSecurity(parentNode); log.debug("getParentNode: {}", parentNode); return parentNode; } catch (HibernateException e) { throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get parent node */ public NodeBase getParentNode(Session session, String uuid) throws HibernateException { log.debug("getParentNode({}, {})", session, uuid); String qs = "from NodeBase nb1 where nb1.uuid = (select nb2.parent from NodeBase nb2 where nb2.uuid=:uuid)"; Query q = session.createQuery(qs); q.setString("uuid", uuid); NodeBase parentNode = (NodeBase) q.setMaxResults(1).uniqueResult(); log.debug("getParentNode: {}", parentNode); return parentNode; } /** * Get parent node permissions */ @SuppressWarnings("unchecked") public NodeBase getParentNodePermissions(Session session, String uuid) throws HibernateException { log.debug("getParentNodePermissions({}, {})", session, uuid); String qs = "select nb1.uuid, index(userPermissions), userPermissions, index(rolePermissions), rolePermissions " + "from NodeBase nb1 join nb1.userPermissions userPermissions join nb1.rolePermissions rolePermissions " + "where nb1.uuid = (select nb2.parent from NodeBase nb2 where nb2.uuid=:uuid)"; Query q = session.createQuery(qs); q.setString("uuid", uuid); List<Object[]> perms = (List<Object[]>) q.list(); NodeBase nBase = null; if (!perms.isEmpty()) { nBase = new NodeBase(); for (Object[] tupla : (List<Object[]>) q.list()) { if (nBase.getUuid() == null) { nBase.setUuid((String) tupla[0]); } if (!nBase.getUserPermissions().containsKey((String) tupla[1])) { nBase.getUserPermissions().put((String) tupla[1], (Integer) tupla[2]); } if (!nBase.getRolePermissions().containsKey((String) tupla[3])) { nBase.getRolePermissions().put((String) tupla[3], (Integer) tupla[4]); } } } log.debug("getParentNodePermissions: {}", nBase); return nBase; } /** * Get result node count. * * @see com.openkm.module.db.DbStatsModule */ public long getCount(String nodeType) throws PathNotFoundException, DatabaseException { log.debug("getCount({})", new Object[] { nodeType }); String qs = "select count(*) from " + nodeType + " nt"; long begin = System.currentTimeMillis(); Session session = null; Transaction tx = null; long total = 0; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); Query q = session.createQuery(qs); total = (Long) q.setMaxResults(1).uniqueResult(); HibernateUtil.commit(tx); log.trace("getCount.Time: {}", System.currentTimeMillis() - begin); log.debug("getCount: {}", total); return total; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get result node count. * * @see com.openkm.module.db.DbStatsModule */ public long getCount(String nodeType, String context) throws PathNotFoundException, DatabaseException { log.debug("getCount({}, {})", new Object[] { nodeType, context }); String qs = "select count(*) from " + nodeType + " nt where nt.context = :context"; long begin = System.currentTimeMillis(); Session session = null; Transaction tx = null; long total = 0; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); Query q = session.createQuery(qs); q.setString("context", PathUtils.fixContext(context)); total = (Long) q.setMaxResults(1).uniqueResult(); HibernateUtil.commit(tx); log.trace("Context: {}, Time: {}", context, System.currentTimeMillis() - begin); log.debug("getCount: {}", total); return total; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get result node count. * * @see com.openkm.module.db.DbStatsModule */ public long getBaseCount(String nodeType, String path) throws PathNotFoundException, DatabaseException { log.debug("getBaseCount({}, {})", new Object[] { nodeType, path }); String qs = "select coalesce(count(*), 0) from NodeFolder n where n.parent=:parent"; long begin = System.currentTimeMillis(); Session session = null; Transaction tx = null; long total = 0; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); String uuid = getUuidFromPath(path); Query q = session.createQuery(qs); q.setString("parent", uuid); total = (Long) q.setMaxResults(1).uniqueResult(); HibernateUtil.commit(tx); log.trace("getBaseCount.Path: {}, Time: {}", path, System.currentTimeMillis() - begin); log.debug("getBaseCount: {}", total); return total; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get result node count. * * @see com.openkm.module.db.DbStatsModule */ public long getSubtreeCount(String nodeType, String path, int depth) throws PathNotFoundException, DatabaseException { log.debug("getSubtreeCount({}, {}, {})", new Object[] { nodeType, path, depth }); long begin = System.currentTimeMillis(); Session session = null; Transaction tx = null; long total = 0; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); String uuid = getUuidFromPath(path); total = getSubtreeCountHelper(session, nodeType, uuid, depth, 1); HibernateUtil.commit(tx); log.trace("getSubtreeCount.Path: {}, Time: {}", path, System.currentTimeMillis() - begin); log.debug("getSubtreeCount: {}", total); return total; } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Helper method. */ @SuppressWarnings("unchecked") private long getSubtreeCountHelper(Session session, String nodeType, String parentUuid, int depth, int level) throws HibernateException, DatabaseException { log.debug("getSubtreeCountHelper({}, {}, {}, {})", new Object[] { nodeType, parentUuid, depth, level }); String qs = "from NodeBase n where n.parent=:parent"; Query q = session.createQuery(qs); q.setString("parent", parentUuid); List<NodeBase> nodes = q.list(); long total = 0; for (NodeBase nBase : nodes) { if (nBase instanceof NodeFolder) { total += getSubtreeCountHelper(session, nodeType, nBase.getUuid(), depth, level + 1); if (NodeFolder.class.getSimpleName().equals(nodeType)) { if (level >= depth) { total += 1; } } } else if (NodeDocument.class.getSimpleName().equals(nodeType) && nBase instanceof NodeDocument) { if (level >= depth) { total += 1; } } } return total; } /** * Check if a subtree contains more than maxNodes nodes */ public boolean subTreeHasMoreThanNodes(String path, long maxNodes) throws PathNotFoundException, DatabaseException { log.debug("subTreeHasMoreThanNodes({}, {})", path, maxNodes); long begin = System.currentTimeMillis(); Session session = null; Transaction tx = null; boolean ret = false; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); String uuid = getUuidFromPath(path); long count = subTreeHasMoreThanNodesHelper(session, uuid, maxNodes, 0); ret = count > maxNodes; HibernateUtil.commit(tx); log.trace("subTreeHasMoreThanNodes.Path: {}, Time: {}", path, System.currentTimeMillis() - begin); log.debug("subTreeHasMoreThanNodes: {}", ret); return ret; } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Helper method. */ @SuppressWarnings("unchecked") private long subTreeHasMoreThanNodesHelper(Session session, String parentUuid, long maxNodes, long curNodes) throws HibernateException, DatabaseException { log.debug("getSubtreeCountHelper({}, {}, {})", new Object[] { parentUuid, maxNodes, curNodes }); String qs = "from NodeBase n where n.parent=:parent"; Query q = session.createQuery(qs); q.setString("parent", parentUuid); List<NodeBase> nodes = q.list(); long total = 0; for (NodeBase nBase : nodes) { if (nBase instanceof NodeDocument) { total += 1; if (total + curNodes > maxNodes) { return total; } } else if (nBase instanceof NodeMail) { total += 1; if (total + curNodes > maxNodes) { return total; } } else if (nBase instanceof NodeFolder) { total += subTreeHasMoreThanNodesHelper(session, nBase.getUuid(), maxNodes, total + curNodes + 1) + 1; if (total + curNodes > maxNodes) { return total; } } } return total; } /** * Check for same node name in same parent * * @param Session Hibernate session. * @param parent Parent node uuid. * @param name Name of the child node to test. * @return true if child item exists or false otherwise. */ public boolean testItemExistence(Session session, String parent, String name) throws HibernateException, DatabaseException { String qs = "from NodeBase nb where nb.parent=:parent and nb.name=:name"; Query q = session.createQuery(qs); q.setString("parent", parent); q.setString("name", name); return !q.list().isEmpty(); } /** * Check for same node name in same parent * * @param session Hibernate session. * @param parent Parent node uuid. * @param name Name of the child node to test. */ public void checkItemExistence(Session session, String parent, String name) throws PathNotFoundException, HibernateException, DatabaseException, ItemExistsException { if (testItemExistence(session, parent, name)) { String path = getPathFromUuid(session, parent); throw new ItemExistsException(path + "/" + name); } } /** * Get node type by UUID */ public String getNodeTypeByUuid(String uuid) throws RepositoryException, PathNotFoundException, DatabaseException { Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); NodeBase nBase = (NodeBase) session.get(NodeBase.class, uuid); if (nBase == null) { throw new PathNotFoundException(uuid); } // Security Check SecurityHelper.checkRead(nBase); if (nBase instanceof NodeFolder) { return Folder.TYPE; } else if (nBase instanceof NodeDocument) { return Document.TYPE; } else if (nBase instanceof NodeMail) { return Mail.TYPE; } else { throw new RepositoryException("Unknown node type"); } } catch (HibernateException e) { throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Add property group */ public void addPropertyGroup(String uuid, String grpName) throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException { log.info("addPropertyGroup({}, {})", uuid, grpName); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); SecurityHelper.checkWrite(node); RegisteredPropertyGroup rpg = (RegisteredPropertyGroup) session.get(RegisteredPropertyGroup.class, grpName); if (rpg != null) { for (String propName : rpg.getProperties().keySet()) { NodeProperty nodProp = new NodeProperty(); nodProp.setNode(node); nodProp.setGroup(rpg.getName()); nodProp.setName(propName); boolean alreadyAssigned = false; for (NodeProperty np : node.getProperties()) { if (np.getGroup().equals(nodProp.getGroup()) && np.getName().equals(nodProp.getName())) { alreadyAssigned = true; break; } } if (!alreadyAssigned) { node.getProperties().add(nodProp); } } } else { HibernateUtil.rollback(tx); throw new RepositoryException("Property Group not registered: " + grpName); } session.update(node); HibernateUtil.commit(tx); log.debug("addPropertyGroup: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Remove property group */ public void removePropertyGroup(String uuid, String grpName) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.debug("removePropertyGroup({}, {})", uuid, grpName); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); SecurityHelper.checkWrite(node); for (Iterator<NodeProperty> it = node.getProperties().iterator(); it.hasNext();) { NodeProperty nodProp = it.next(); if (grpName.equals(nodProp.getGroup())) { it.remove(); session.delete(nodProp); } } session.update(node); HibernateUtil.commit(tx); log.debug("removePropertyGroup: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get assigned property groups */ @SuppressWarnings("unchecked") public List<String> getPropertyGroups(String uuid) throws PathNotFoundException, DatabaseException { log.debug("getPropertyGroups({}, {})", uuid); String qs = "select distinct(nbp.group) from NodeBase nb join nb.properties nbp where nb.uuid=:uuid"; Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); Query q = session.createQuery(qs); q.setString("uuid", uuid); List<String> ret = q.list(); HibernateUtil.commit(tx); log.debug("getPropertyGroups: {}", ret); return ret; } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get properties from property group */ public Map<String, String> getProperties(String uuid, String grpName) throws PathNotFoundException, DatabaseException { log.debug("getProperties({}, {})", uuid, grpName); long begin = System.currentTimeMillis(); Map<String, String> ret = new HashMap<String, String>(); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); for (NodeProperty nodProp : node.getProperties()) { if (grpName.equals(nodProp.getGroup())) { ret.put(nodProp.getName(), nodProp.getValue()); } } HibernateUtil.commit(tx); log.trace("getProperties.Time: {}", System.currentTimeMillis() - begin); log.debug("getProperties: {}", ret); return ret; } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Get single property value from property group */ public String getProperty(String uuid, String grpName, String propName) throws PathNotFoundException, DatabaseException { log.debug("getProperty({}, {}, {})", new Object[] { uuid, grpName, propName }); long begin = System.currentTimeMillis(); String propValue = null; Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); for (NodeProperty nodProp : node.getProperties()) { if (grpName.equals(nodProp.getGroup()) && propName.equals(nodProp.getName())) { propValue = nodProp.getValue(); break; } } HibernateUtil.commit(tx); log.trace("getProperty.Time: {}", System.currentTimeMillis() - begin); log.debug("getProperty: {}", propValue); return propValue; } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Set properties from property group */ public Map<String, String> setProperties(String uuid, String grpName, Map<String, String> properties) throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException { log.debug("setProperties({}, {}, {})", new Object[] { uuid, grpName, properties }); Map<String, String> ret = new HashMap<String, String>(); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase node = (NodeBase) session.load(NodeBase.class, uuid); SecurityHelper.checkRead(node); SecurityHelper.checkWrite(node); Set<NodeProperty> tmp = new HashSet<NodeProperty>(); for (Entry<String, String> prop : properties.entrySet()) { boolean alreadyAssigned = false; // Set new property group values for (NodeProperty nodProp : node.getProperties()) { if (grpName.equals(nodProp.getGroup()) && prop.getKey().equals(nodProp.getName())) { log.debug("UPDATE - Group: {}, Property: {}, Value: {}", new Object[] { grpName, prop.getKey(), prop.getValue() }); nodProp.setValue(prop.getValue()); alreadyAssigned = true; // TODO: Workaround for Hibernate Search tmp.add(nodProp); } else if (nodProp.getValue() != null && !nodProp.getValue().isEmpty()) { if (!tmp.contains(nodProp)) { log.debug("KEEP - Group: {}, Property: {}, Value: {}", new Object[]{nodProp.getGroup(), nodProp.getName(), nodProp.getValue()}); // TODO: Workaround for Hibernate Search tmp.add(nodProp); } } } if (!alreadyAssigned) { log.debug("ADD - Group: {}, Property: {}, Value: {}", new Object[] { grpName, prop.getKey(), prop.getValue() }); NodeProperty nodProp = new NodeProperty(); nodProp.setNode(node); nodProp.setGroup(grpName); nodProp.setName(prop.getKey()); nodProp.setValue(prop.getValue()); // TODO: Workaround for Hibernate Search tmp.add(nodProp); } } node.setProperties(tmp); session.update(node); HibernateUtil.commit(tx); log.debug("setProperties: {}", ret); return ret; } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Fix node stored path. Also valid for initialize when upgrading. */ @SuppressWarnings("unchecked") public void fixNodePath() throws DatabaseException { log.debug("fixNodePath()"); String qs = "from NodeBase nb where nb.parent=:parent"; Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // First level nodes Query q = session.createQuery(qs); q.setString("parent", Config.ROOT_NODE_UUID); for (NodeBase nb : (List<NodeBase>) q.list()) { nb.setPath("/" + nb.getName()); session.update(nb); // Process in depth fixNodePathHelper(session, nb); } HibernateUtil.commit(tx); log.debug("fixNodePath: void"); } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } @SuppressWarnings("unchecked") private void fixNodePathHelper(Session session, NodeBase parentNode) throws HibernateException { String qs = "from NodeBase nb where nb.parent=:parent"; Query q = session.createQuery(qs); q.setString("parent", parentNode.getUuid()); for (NodeBase nb : (List<NodeBase>) q.list()) { nb.setPath(parentNode.getPath() + "/" + nb.getName()); session.update(nb); // Process in depth fixNodePathHelper(session, nb); } } public void copyAttributes(String srcUuid, String dstUuid, ExtendedAttributes extAttr) throws PathNotFoundException, AccessDeniedException, DatabaseException { log.info("copyAttributes({}, {}, {})", new Object[] { srcUuid, dstUuid, extAttr }); Session session = null; Transaction tx = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); // Security Check NodeBase srcNode = (NodeBase) session.load(NodeBase.class, srcUuid); SecurityHelper.checkRead(srcNode); NodeBase dstNode = (NodeBase) session.load(NodeBase.class, dstUuid); SecurityHelper.checkRead(dstNode); SecurityHelper.checkWrite(dstNode); if (extAttr != null) { if (extAttr.isKeywords()) { Set<String> keywords = srcNode.getKeywords(); dstNode.setKeywords(CloneUtils.clone(keywords)); } if (extAttr.isCategories()) { Set<String> categories = srcNode.getCategories(); dstNode.setCategories(CloneUtils.clone(categories)); } if (extAttr.isPropertyGroups()) { Set<NodeProperty> propertyGroups = srcNode.getProperties(); for (NodeProperty nProp : CloneUtils.clone(propertyGroups)) { nProp.setNode(dstNode); dstNode.getProperties().add(nProp); } } if (extAttr.isNotes()) { List<NodeNote> notes = NodeNoteDAO.getInstance().findByParent(srcNode.getUuid()); for (NodeNote nNote : CloneUtils.clone(notes)) { BaseNoteModule.create(dstNode.getUuid(), nNote.getAuthor(), nNote.getText()); } } } session.update(dstNode); HibernateUtil.commit(tx); log.debug("copyAttributes: void"); } catch (PathNotFoundException e) { HibernateUtil.rollback(tx); throw e; } catch (AccessDeniedException e) { HibernateUtil.rollback(tx); throw e; } catch (DatabaseException e) { HibernateUtil.rollback(tx); throw e; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } finally { HibernateUtil.close(session); } } /** * Force initialization of a proxy */ public void initialize(NodeBase nBase) { if (nBase != null) { Hibernate.initialize(nBase); Hibernate.initialize(nBase.getKeywords()); Hibernate.initialize(nBase.getCategories()); Hibernate.initialize(nBase.getSubscriptors()); Hibernate.initialize(nBase.getUserPermissions()); Hibernate.initialize(nBase.getRolePermissions()); } } /** * Force initialization of a proxy */ public void initializeSecurity(NodeBase nBase) { if (nBase != null) { Hibernate.initialize(nBase); Hibernate.initialize(nBase.getUserPermissions()); Hibernate.initialize(nBase.getRolePermissions()); } } }
package controller; import java.time.LocalDate; import java.time.LocalTime; import java.util.ArrayList; import java.util.List; import ordination.DagligFast; import ordination.DagligSkaev; import ordination.Laegemiddel; import ordination.Ordination; import ordination.PN; import ordination.Patient; import storage.Storage; public class Controller { private Storage storage; private static Controller controller; private Controller() { this.storage = new Storage(); } //tilføjet get-metode til at teste antalOrdinationerPrVægtPrLægemiddel i jUnit public Storage getStorage() { return storage; } public static Controller getController() { if (controller == null) { controller = new Controller(); } return controller; } public static Controller getTestController() { return new Controller(); } /** * Hvis startDato er efter slutDato kastes en IllegalArgumentException og * ordinationen oprettes ikke * Pre: startDen, slutDen, patient og laegemiddel er ikke null * * @return opretter og returnerer en PN ordination. */ public PN opretPNOrdination(LocalDate startDen, LocalDate slutDen, Patient patient, Laegemiddel laegemiddel, double antal) { if (checkStartFoerSlut(startDen, slutDen) == true) { PN pn = new PN(startDen, slutDen, antal); pn.setLaegemiddel(laegemiddel); patient.addOrdination(pn); return pn; } else { throw new IllegalArgumentException("Ordinationen oprettes ikke "); } } /** * Opretter og returnerer en DagligFast ordination. Hvis startDato er efter * slutDato kastes en IllegalArgumentException og ordinationen oprettes ikke * Pre: startDen, slutDen, patient og laegemiddel er ikke null */ public DagligFast opretDagligFastOrdination(LocalDate startDen, LocalDate slutDen, Patient patient, Laegemiddel laegemiddel, double morgenAntal, double middagAntal, double aftenAntal, double natAntal) { if (checkStartFoerSlut(startDen, slutDen) && (morgenAntal >= 0) && (middagAntal >= 0) && (aftenAntal >= 0) && (natAntal >= 0) ) { DagligFast dagligFast = new DagligFast(startDen, slutDen); dagligFast.setLaegemiddel(laegemiddel); dagligFast.createDosis(LocalTime.of(6, 00), morgenAntal); dagligFast.createDosis(LocalTime.of(12, 00), middagAntal); dagligFast.createDosis(LocalTime.of(18, 00), aftenAntal); dagligFast.createDosis(LocalTime.of(00, 00), natAntal); patient.addOrdination(dagligFast); return dagligFast; } else { throw new IllegalArgumentException("Ordinationen oprettes ikke "); } } /** * Opretter og returnerer en DagligSkæv ordination. Hvis startDato er efter * slutDato kastes en IllegalArgumentException og ordinationen oprettes ikke. * Hvis antallet af elementer i klokkeSlet og antalEnheder er forskellige kastes også en IllegalArgumentException. * * Pre: startDen, slutDen, patient og laegemiddel er ikke null */ public DagligSkaev opretDagligSkaevOrdination(LocalDate startDen, LocalDate slutDen, Patient patient, Laegemiddel laegemiddel, LocalTime[] klokkeSlet, double[] antalEnheder) { if (checkStartFoerSlut(startDen, slutDen) == true) { DagligSkaev dagligSkaev = new DagligSkaev(startDen, slutDen); dagligSkaev.setLaegemiddel(laegemiddel); for (int i = 0; i < klokkeSlet.length; i++) { dagligSkaev.createDosis(klokkeSlet[i], antalEnheder[i]); } patient.addOrdination(dagligSkaev); return dagligSkaev; } else { throw new IllegalArgumentException("Ordinationen oprettes ikke "); } } /** * En dato for hvornår ordinationen anvendes tilføjes ordinationen. Hvis * datoen ikke er indenfor ordinationens gyldighedsperiode kastes en * IllegalArgumentException * Pre: ordination og dato er ikke null */ public void ordinationPNAnvendt(PN ordination, LocalDate dato) { if (dato.isBefore(ordination.getStartDen()) || dato.isAfter(ordination.getSlutDen())) { throw new IllegalArgumentException("Ordinationen oprettes ikke "); } else { ordination.givDosis(dato); } } /** * Den anbefalede dosis for den pågældende patient (der skal tages hensyn * til patientens vægt). Det er en forskellig enheds faktor der skal * anvendes, og den er afhængig af patientens vægt. * Pre: patient og lægemiddel er ikke null */ public double anbefaletDosisPrDoegn(Patient patient, Laegemiddel laegemiddel) { double result; if (patient.getVaegt() < 25) { result = patient.getVaegt() * laegemiddel.getEnhedPrKgPrDoegnLet(); } else if (patient.getVaegt() > 120) { result = patient.getVaegt() * laegemiddel.getEnhedPrKgPrDoegnTung(); } else { result = patient.getVaegt() * laegemiddel.getEnhedPrKgPrDoegnNormal(); } return result; } /** * For et givent vægtinterval og et givent lægemiddel, hentes antallet af * ordinationer. * Pre: laegemiddel er ikke null */ public int antalOrdinationerPrVægtPrLægemiddel(double vægtStart, double vægtSlut, Laegemiddel laegemiddel) { int antal = 0; List<Patient> patienterIInterval = new ArrayList<>(); //hent alle patienter fra det givne vægtinterval for (Patient p : this.storage.getAllPatienter()) { if (vægtStart <= p.getVaegt() && p.getVaegt() <= vægtSlut) { patienterIInterval.add(p); } } //for patienterne tjekkes om de ordinationer de har fået svarer til det givne laegemiddel for (Patient p : patienterIInterval) { for (Ordination o : p.getOrdinationer()) { if (o.getLaegemiddel().equals(laegemiddel)) { antal++; } } } return antal; } public List<Patient> getAllPatienter() { return this.storage.getAllPatienter(); } public List<Laegemiddel> getAllLaegemidler() { return this.storage.getAllLaegemidler(); } /** * Metode der kan bruges til at checke at en startDato ligger før en * slutDato. * * @return true hvis startDato er før slutDato, false ellers. */ private boolean checkStartFoerSlut(LocalDate startDato, LocalDate slutDato) { boolean result = true; if (slutDato.compareTo(startDato) < 0) { result = false; } return result; } public Patient opretPatient(String cpr, String navn, double vaegt) { Patient p = new Patient(cpr, navn, vaegt); this.storage.addPatient(p); return p; } public Laegemiddel opretLaegemiddel(String navn, double enhedPrKgPrDoegnLet, double enhedPrKgPrDoegnNormal, double enhedPrKgPrDoegnTung, String enhed) { Laegemiddel lm = new Laegemiddel(navn, enhedPrKgPrDoegnLet, enhedPrKgPrDoegnNormal, enhedPrKgPrDoegnTung, enhed); this.storage.addLaegemiddel(lm); return lm; } public void createSomeObjects() { opretPatient("121256-0512", "Jane Jensen", 63.4); opretPatient("070985-1153", "Finn Madsen", 83.2); opretPatient("050972-1233", "Hans Jørgensen", 89.4); opretPatient("011064-1522", "Ulla Nielsen", 59.9); opretPatient("090149-2529", "Ib Hansen", 87.7); opretLaegemiddel("Acetylsalicylsyre", 0.1, 0.15, 0.16, "Styk"); opretLaegemiddel("Paracetamol", 1, 1.5, 2, "Ml"); opretLaegemiddel("Fucidin", 0.025, 0.025, 0.025, "Styk"); opretLaegemiddel("Methotrexat", 0.01, 0.015, 0.02, "Styk"); opretPNOrdination(LocalDate.of(2019, 1, 1), LocalDate.of(2019, 1, 12), this.storage.getAllPatienter().get(0), this.storage.getAllLaegemidler() .get(1), 123); opretPNOrdination(LocalDate.of(2019, 2, 12), LocalDate.of(2019, 2, 14), this.storage.getAllPatienter().get(0), this.storage.getAllLaegemidler() .get(0), 3); opretPNOrdination(LocalDate.of(2019, 1, 20), LocalDate.of(2019, 1, 25), this.storage.getAllPatienter().get(3), this.storage.getAllLaegemidler() .get(2), 5); opretPNOrdination(LocalDate.of(2019, 1, 1), LocalDate.of(2019, 1, 12), this.storage.getAllPatienter().get(0), this.storage.getAllLaegemidler() .get(1), 123); //Nedenstående kode har vi valgt at udkommenterer, da den var ugyldig pga. ugyldige enheder og derved //forårsagede fejl i programmet ved opstart // opretDagligFastOrdination(LocalDate.of(2019, 1, 10), // LocalDate.of(2019, 1, 12), this.storage.getAllPatienter().get(1), // this.storage.getAllLaegemidler().get(1), 2, -1, 1, -1); LocalTime[] kl = { LocalTime.of(12, 0), LocalTime.of(12, 40), LocalTime.of(16, 0), LocalTime.of(18, 45) }; double[] an = { 0.5, 1, 2.5, 3 }; opretDagligSkaevOrdination(LocalDate.of(2019, 1, 23), LocalDate.of(2019, 1, 24), this.storage.getAllPatienter().get(1), this.storage.getAllLaegemidler().get(2), kl, an); } }
/** * JVM에 의해 자동 생성되는 main 스레드에 의해 자동 호출되는 엔트리포인트 * @author 이대용 * */ public class ThreadExample { public static void main(String[] args) throws InterruptedException { System.out.println("메인스레드 시작됨..."); for (int i=0; i<100; i++) { System.out.println("메인스레드 i 출력: " + i); Thread.sleep(100); if (i == 50) { UserThread thread = new UserThread("class5"); // 스레드스케쥴러에 사용자스레드 등록 thread.start(); new Thread() { @Override public void run() { System.out.println("음악재생"); } }.start(); UserThread2 thread2 = new UserThread2(); thread2.setSize(500,500); thread2.setVisible(true); new Thread(thread2).start();; } } System.out.println("메인스레드 종료됨..."); } }
package edu.curtin.comp2008.mad2020assignment1; import androidx.fragment.app.Fragment; /** * WhichFrag is an interface that contains changeFrag and changeFragRowCol method */ public interface WhichFrag { //changeFrag method will be used to change the fragment, between FragAHorizontal and FragAVertical void changeFrag(Fragment frag); //changeFragRowCol method will be used to change the row or col and the layout of the fragment void changeFragRowCol(int rowCol, String fragChosen); }
package com.app.sapient.grade.dto; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; @Getter @Setter @JsonInclude(value = Include.NON_NULL) public class StudentDto { @JsonProperty("id") private Long id; @JsonProperty("name") private String name; @JsonProperty("gradeItemDtos") private List<GradeItemDto> gradeItemDtos; @JsonProperty("gradeAsPercent") private Double gradeAsPercent; }
package edu.upc.entity; import android.util.Log; import android.util.JsonReader; import android.util.JsonWriter; import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.Proxy; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import org.json.JSONTokener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONStringer; public class MessageREST { public static void REST_create(String server, String port, DMessages message) { try { // create URL object with url: // http://server_ip:port/Netbeans_project_name/webresources/ // package_name.message // open url connection //URL url = new URL("http://10.0.2.2:29547/D_Dispositius/webresources/practica2.dmessages/from"); URL url = new URL("http://"+server+":"+port+"/D_Dispositius/webresources/practica2.dmessages/"); HttpURLConnection ucon = (HttpURLConnection)url.openConnection(); ucon.setConnectTimeout(8000); // set POST request method, DoInput and DoOutput // set "application/json" MIME type for both sending and receiving try { ucon.setRequestMethod("POST"); } catch (ProtocolException e) { System.out.println("Failed to set to POST"); e.printStackTrace(); } ucon.setDoOutput(true); ucon.setRequestProperty("Content-Type", "application/json; charset=utf-8"); ucon.setRequestProperty("Accept", "application/json"); JSONObject messageAsJson = new JSONObject(); messageAsJson.put("content", message.getContent()); messageAsJson.put("date", message.getDate()); messageAsJson.put("userSender", message.getUserSender()); messageAsJson.put("id", message.getId()); System.out.println(message.toString()); String urlParameters = messageAsJson.toString(); DataOutputStream writter = new DataOutputStream(ucon.getOutputStream()); writter.writeBytes(urlParameters); writter.flush(); writter.close(); ucon.connect(); int tmp = ucon.getResponseCode(); Log.i("Tests", "TMP is " + tmp); if(tmp == HttpURLConnection.HTTP_OK) { Log.i("Tests", "Connection ok"); } else { Log.i("Tests", "Connection failed"); } // open BufferedReader attached to url InputStream // read response and optionally print to System.out //TODO ... } catch (Exception e) { e.printStackTrace(); } } public static ArrayList<DMessages> REST_retrieveFromDate(String server, String port, Date date, String nick) { try { // create URL object with url: // http://server_ip:port/Netbeans_project_name/webresources/ // package_name.message/from // open url connection //10.0.2.2 //8080 URL url = new URL("http://"+server+":"+port+"/D_Dispositius/webresources/practica2.dmessages/from"); //URL url = new URL("http://10.0.2.2:29547/D_Dispositius/webresources/practica2.dmessages/from"); HttpURLConnection ucon = (HttpURLConnection)url.openConnection(); ucon.setConnectTimeout(8000); // set POST request method, DoInput and DoOutput // set "application/json" MIME type for both sending and receiving try { ucon.setRequestMethod("POST"); } catch (ProtocolException e) { System.out.println("Failed to set to POST"); e.printStackTrace(); } ucon.setDoInput(true); ucon.setDoOutput(true); ucon.setRequestProperty("Content-Type", "application/json; charset=utf-8"); ucon.setRequestProperty("Accept", "application/json"); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+01:00"); JSONObject dateAsObj = new JSONObject(); dateAsObj.put("date", date); System.out.println(dateAsObj.toString()); String urlParameters = dateAsObj.toString(); DataOutputStream writter = new DataOutputStream(ucon.getOutputStream()); writter.writeBytes(urlParameters); writter.flush(); writter.close(); ucon.connect(); int tmp = ucon.getResponseCode(); Log.i("Tests", "TMP is " + tmp); if(tmp == HttpURLConnection.HTTP_OK) { Log.i("Tests", "Connection ok"); } else { Log.i("Tests", "Connection failed"); } ArrayList<DMessages> messages = new ArrayList<>(); BufferedReader in = new BufferedReader(new InputStreamReader(ucon.getInputStream())); for(JsonElement el: new JsonParser().parse(in).getAsJsonArray()) { messages.add(new Gson().fromJson(el, DMessages.class)); } return messages; } catch (Exception e) { e.printStackTrace(); return null; } } static public DMessages readMessage(JsonReader reader) throws IOException { String content = null; Date date = null; String sender = null; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); switch (name) { case "content": content = reader.nextString(); break; case "user_sender": sender = reader.nextString(); break; case "date": date = new Date(); date.parse(reader.nextString()); break; default: reader.skipValue(); break; } } reader.endObject(); return new DMessages(0, content, sender, date); } }
package com.epam.bar.dao; import com.epam.bar.entity.User; import com.epam.bar.exception.DaoException; import java.util.Optional; /** * @author Kirill Karalionak * @version 1.0.0 */ public abstract class AbstractUserDao extends BaseDao<String, User> { /** * Find password * * @param key the key * @return the string * @throws DaoException the dao exception */ public abstract String findPassword(String key) throws DaoException; /** * Add {@link User} * * @param entity the entity * @param password the password * @return the boolean * @throws DaoException the dao exception */ public abstract boolean add(User entity, String password) throws DaoException; /** * Find {@link User} by field * * @param key the key * @param field the field * @return the optional * @throws DaoException the dao exception */ public abstract Optional<User> findByField(String key, UserField field) throws DaoException; }
package com.rochards.personapi.dto.request; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.validator.constraints.br.CPF; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.util.List; /* * Essas classes de DTO serve para validar os dados de entrada antes mesmo de * chegar nos models/entidades * */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class PersonDTO { private Long id; @NotBlank @Size(min = 2, max = 100) private String firstName; @NotBlank @Size(min = 2, max = 100) private String lastName; @NotBlank @CPF // o CPF vem do hibernate validator private String cpf; private String birthDate; @NotEmpty @Valid // o @valid vai dizer para validar os campos de telefone private List<PhoneDTO> phones; }
package com.dorothy.railway999.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.dorothy.railway999.annotation.Auth; import com.dorothy.railway999.vo.MemberVo; public class AuthInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Auth auth = ( ( HandlerMethod ) handler ).getMethodAnnotation( Auth.class ); if( auth == null ) { return true; } HttpSession session = request.getSession(); if( session == null ) { response.sendRedirect("/railway999/"); return false; } MemberVo authMember = (MemberVo)session.getAttribute( "AuthMember" ); if( authMember == null ) { response.sendRedirect( "/railway999/"); return false; } if( auth.role().equals("Admin") && !"admin".equals(authMember.getRole())){ response.sendRedirect( "/railway999/"); return false; } return true; } }
package com.tencent.mm.plugin.mall.ui; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.tencent.mm.ab.l; import com.tencent.mm.bg.d; import com.tencent.mm.k.g; import com.tencent.mm.model.q; import com.tencent.mm.platformtools.ab; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.plugin.wallet_core.model.ac; import com.tencent.mm.plugin.wallet_core.model.mall.MallFunction; import com.tencent.mm.plugin.wallet_core.model.o; import com.tencent.mm.plugin.wxpay.a; import com.tencent.mm.plugin.wxpay.a$f; import com.tencent.mm.plugin.wxpay.a$g; import com.tencent.mm.pluginsdk.ui.applet.CdnImageView; import com.tencent.mm.protocal.c.ccp; import com.tencent.mm.protocal.c.ccq; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.wallet_core.ui.e; public class MallIndexOSUI extends MallIndexBaseUI { private boolean fWB = false; private View hsd = null; private TextView kZA = null; private boolean kZB = false; private long kZC = 0; private boolean kZD = false; private boolean kZE = false; private String kZF = ""; private c kZG = new 1(this); private c kZH = new 2(this); private a[] kZy = new a[4]; private ac kZz = new ac(); private long lastUpdateTime = 0; public void onCreate(Bundle bundle) { super.onCreate(bundle); this.hsd = View.inflate(this, a$g.mall_index_foot, null); this.hsd.setClickable(false); this.hsd.setEnabled(false); this.kZA = (TextView) this.hsd.findViewById(a$f.wallet_region_desc); this.kZz = o.bPc().zo(this.kYc); jr(1577); x.i("MicroMsg.MallIndexOSUI", "walletMallIndexOsUI "); com.tencent.mm.plugin.mall.a.c cVar = new com.tencent.mm.plugin.mall.a.c(); if (this.kZz != null) { ac acVar = this.kZz; boolean z = acVar.pro == null || acVar.pro.rFB == null || acVar.pro.rFB.size() == 0; if (!z) { a(cVar, false, false); return; } } a(cVar, true, false); } protected final void bbW() { e.a(this.kZm, "1", this.kZz.prt, this.kZz.kRf); } public final void a(MallFunction mallFunction, int i) { super.a(mallFunction, i); h.mEJ.h(13720, new Object[]{mallFunction.kck, Long.valueOf(bi.WV(mallFunction.moy))}); } protected final void bbO() { String str = this.kZz.prr; String str2 = this.kZz.prs; setMMTitle(str); setMMSubTitle(str2); } protected final void cs(View view) { this.kZy[0] = new a(this); this.kZy[0].view = view.findViewById(a$f.offline_area); this.kZy[0].kYr = (CdnImageView) view.findViewById(a$f.offline_pic); this.kZy[0].hND = (TextView) view.findViewById(a$f.offline_wording); this.kZy[0].kZO = (TextView) view.findViewById(a$f.extra_wording_first); this.kZy[0].kYr.setVisibility(4); this.kZy[1] = new a(this); this.kZy[1].view = view.findViewById(a$f.balance_area); this.kZy[1].kYr = (CdnImageView) view.findViewById(a$f.balance_pic); this.kZy[1].hND = (TextView) view.findViewById(a$f.balance_wording); this.kZy[1].kZO = (TextView) view.findViewById(a$f.balance_num); this.kZy[1].kYr.setVisibility(4); this.kZy[2] = new a(this); this.kZy[2].view = view.findViewById(a$f.bankcard_area); this.kZy[2].kYr = (CdnImageView) view.findViewById(a$f.bankcard_pic); this.kZy[2].hND = (TextView) view.findViewById(a$f.bankcard_tv); this.kZy[2].kZO = (TextView) view.findViewById(a$f.extra_wording_three); this.kZy[2].kYr.setVisibility(4); this.kZy[3] = new a(this); this.kZy[3].view = view.findViewById(a$f.lqt_area); this.kZy[3].kYr = (CdnImageView) view.findViewById(a$f.lqt_pic); this.kZy[3].hND = (TextView) view.findViewById(a$f.lqt_wording); this.kZy[3].kYr.setVisibility(4); this.kZy[3].view.setVisibility(8); } protected final void bbP() { } protected final void bbQ() { } public void onResume() { super.onResume(); x.d("MicroMsg.MallIndexOSUI", "checkUpdate svrTime: %d lastUpdateTime : %d curTime %d", new Object[]{Integer.valueOf(g.AT().getInt("OverseaPayWalletInfoRefreshInternal", 15) * 1000), Long.valueOf(this.lastUpdateTime), Long.valueOf(System.currentTimeMillis())}); if (System.currentTimeMillis() - this.lastUpdateTime >= ((long) (g.AT().getInt("OverseaPayWalletInfoRefreshInternal", 15) * 1000))) { this.lastUpdateTime = System.currentTimeMillis(); a(new com.tencent.mm.plugin.mall.a.c(), false, false); } bbO(); } public void onPause() { super.onPause(); } public void onDestroy() { super.onDestroy(); js(1577); this.kZG.dead(); this.kZH.dead(); } protected final boolean bbS() { ccp ccp = this.kZz.pro; for (int i = 0; i < this.kZy.length; i++) { this.kZy[i].view.setVisibility(8); this.kZy[i].kYr.setImageBitmap(null); } int i2 = 0; while (i2 < ccp.rFB.size() && i2 < this.kZy.length) { ccq ccq = (ccq) ccp.rFB.get(i2); this.kZy[i2].view.setVisibility(0); this.kZy[i2].kYr.setUrl(ab.a(ccq.syq)); this.kZy[i2].kYr.setVisibility(0); this.kZy[i2].hND.setText(ab.a(ccq.syp)); x.i("MicroMsg.MallIndexOSUI", "item %d url %s", new Object[]{Integer.valueOf(i2), ab.a(ccq.syq)}); this.kZy[i2].kZO.setVisibility(8); CharSequence a = ab.a(ccq.sys); if (!bi.oW(a)) { this.kZy[i2].kZO.setText(a); this.kZy[i2].kZO.setVisibility(0); } this.kZy[i2].view.setOnClickListener(new 3(this, ccq)); i2++; } if (!(this.kZh == null || this.hsd == null || this.kZB)) { this.kZh.addFooterView(this.hsd); this.kZB = true; } if (!bi.oW(this.kZz.pru)) { this.kZA.setText(this.kZz.pru); this.kZA.setVisibility(0); } return true; } protected final void bbX() { } protected final void bbZ() { this.mController.removeAllOptionMenu(); addIconOptionMenu(0, a.e.mm_title_btn_menu, new 4(this)); } protected final void bca() { } public void finish() { this.fWB = true; super.finish(); } public final boolean d(int i, int i2, String str, l lVar) { super.d(i, i2, str, lVar); if (lVar.getType() == 1577) { com.tencent.mm.plugin.mall.a.c cVar = (com.tencent.mm.plugin.mall.a.c) lVar; if ((cVar.kYf == null ? 0 : cVar.kYf.syt) == 1 && !bi.oW(cVar.bbI())) { if (!this.fWB) { if (System.currentTimeMillis() - this.kZC > 500) { this.kZC = System.currentTimeMillis(); this.kZG.cht(); this.kZH.cht(); Bundle bundle = new Bundle(); this.kZF = cVar.bbI(); Intent intent = new Intent(); x.i("MicroMsg.MallIndexOSUI", "startWebViewUI %s", new Object[]{this.kZF}); bundle.putString("KoriginUrl", this.kZF); bundle.putBoolean("KIsHKAgreeUrl", true); intent.putExtra("rawUrl", this.kZF); intent.putExtra("jsapiargs", bundle); intent.putExtra("geta8key_username", q.GF()); intent.putExtra("pay_channel", 1); d.b(this, "webview", "com.tencent.mm.plugin.webview.ui.tools.WebViewUI", intent, 4); } } } this.kZz = o.bPc().zo(this.kYc); bbW(); bbS(); bbO(); } return true; } protected void onActivityResult(int i, int i2, Intent intent) { x.i("MicroMsg.MallIndexOSUI", "onActivityResult requestCode %s resultCode %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}); super.onActivityResult(i, i2, intent); } }
package switch2019.project.utils.customExceptions; public class NoPermissionException extends RuntimeException { public NoPermissionException (String message) { super (message); } }
package quoai.challenge; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.net.URL; import java.net.URLConnection; import java.util.zip.GZIPInputStream; public class Test { static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"; public static void main(String[] args) { try { // This user agent is for if the server wants real humans to visit URL url = new URL("https://data.gharchive.org/2015-01-01-15.json.gz"); URLConnection con = url.openConnection(); con.setRequestProperty("User-Agent", USER_AGENT); GZIPInputStream gzip = new GZIPInputStream( con.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(gzip)); String content; int size = 0; while ((content = br.readLine()) != null) { System.out.println(content); size++; } System.out.println("Count: " + size); } catch (IOException e) { e.printStackTrace(); } } }
package couchbase.sample.report; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import couchbase.sample.json.ClusterMapObj; import couchbase.sample.util.CBRestAPIUtil; import couchbase.sample.vo.Server; public class ClusterStatReport extends BaseReport { public static String INDEX = "index"; public static String DATA = "kv"; public static String FTS = "fts"; public static String QUERY = "n1ql"; /** * * @param queryHostname * @param user * @param password * @return A HashMap with key as the name of the service (like fts, kv, n1ql etc) and value as the List<String> of hostname */ protected HashMap<String, ArrayList<String>> getClusterMap(String queryHostname, String user, String password){ HashMap<String, ArrayList<String>> clusterMap = new HashMap<String, ArrayList<String>>(); String queryStmt = super.getQueryStmtForClusterMap(queryHostname, user, password); try { //run REST call to get the cluster map String resultJson = CBRestAPIUtil.getPOSTServiceOutput(super.getQueryServiceURL(queryHostname), queryStmt); //convert resultJson to ClusterMapObj ClusterMapObj clusterMapObj = ClusterMapObj.fromJson(resultJson); if(clusterMapObj !=null) { //get servers from the clusterMap object List<Server> servers = new ArrayList<Server>(); servers = clusterMapObj.getResults(); String hostname = null; List<String> serviceHosts = null; //now iterate through each and populate the map for(Server server: servers) { hostname = server.getHostname(); //remove :port from the hostname hostname = hostname.substring(0, hostname.indexOf(':')); List<String> services = server.getServices(); for(String serviceName: services) { //if service already exist then add this hostname to the list if(clusterMap.containsKey(serviceName)){ serviceHosts = clusterMap.get(serviceName); //add new host to the list serviceHosts.add(hostname); }else { //create a new list of serviceHost and add it for the serviceName as the key ArrayList<String> hostnames = new ArrayList<String>(); hostnames.add(hostname); //add this list to the map with serviceName as the key clusterMap.put(serviceName, hostnames); } }//eof for }//eof for }//eof if System.out.println(clusterMap); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return clusterMap; } //getClusterMap() protected HashMap<String, ArrayList<String>> getResidentRatioForIndexes(String queryHostname, String user, String password){ String queryStmt = null; String resultJson = null; //get cluster map definition first HashMap<String, ArrayList<String>> clusterMap = this.getClusterMap(queryHostname, user, password); //System.out.println(clusterMap); if(clusterMap != null) { //get all index types ArrayList<String> indexHosts = clusterMap.get(INDEX); //System.out.println(indexHosts); //iterate through the list and display resident ratios of each index in the index node for(String indexHostname: indexHosts) { queryStmt = super.getQueryMemoryResidentIndex(indexHostname, user, password); try { //run REST call to get the cluster map resultJson = CBRestAPIUtil.getPOSTServiceOutput(getQueryServiceURL(queryHostname), queryStmt); System.out.println(resultJson); }catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }//EOF for }//EOF if(clusterMap!=null) return clusterMap; } //getClusterMap() public static void main(String[] args) { ClusterStatReport clusterStatReport = new ClusterStatReport(); try { //clusterStatReport.getClusterMap("ec2-54-202-253-193.us-west-2.compute.amazonaws.com", "Administrator", "p0lar1s"); clusterStatReport.getResidentRatioForIndexes("ec2-52-12-206-206.us-west-2.compute.amazonaws.com", "Administrator", "p0lar1s"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }//main }
package com.ibm.ive.tools.japt.obfuscation; import java.util.*; import com.ibm.jikesbt.*; import com.ibm.ive.tools.japt.*; /** * Encapsulates functionality to rename the methods and fields of a single class. * <p> * Will also rename related methods of separate classes and interfaces, such as overriding or overridden methods. * @author sfoley */ class RenameableClass { private final BT_Class clazz; private final NameGenerator nameGenerator = new NameGenerator(); private ConstantPoolNameGenerator constantPoolNameGenerator; private final UsedNameGenerator usedMethodNameGenerator = new UsedNameGenerator(); private final UsedNameGenerator unusedGeneratedMethodNames = new UsedNameGenerator(); private final NameHandler nameHandler; private final RelatedNameCollectorCreator nameCollectorCreator; private final RelatedMethodMap relatedMethodMap; //private final boolean caseSensitive; private boolean prepend; RenameableClass(BT_Class clazz, NameHandler nameHandler, RelatedMethodMap relatedMethodMap, RelatedNameCollectorCreator rncc, boolean reuseConstantPoolNames, boolean prepend) { this.clazz = clazz; this.nameHandler = nameHandler; this.nameCollectorCreator = rncc; this.relatedMethodMap = relatedMethodMap; BT_MethodVector methods = clazz.getMethods(); for(int i=0; i<methods.size(); i++) { BT_Method method = methods.elementAt(i); if(nameHandler.nameIsFixed(method) && !StandardNameFixer.isStandardMethod(method)) { usedMethodNameGenerator.add(method.getName()); } } if(reuseConstantPoolNames) { try { constantPoolNameGenerator = new ConstantPoolNameGenerator(clazz); } catch(BT_ClassFileException e) {} } this.prepend = prepend; } private void renameField(BT_Field field) { String newName; if(prepend) { newName = '_' + field.getName(); while(fieldNameIsUnavailable(field, newName)) { newName = '_' + newName; } } else { newName = getNextFieldName(field); } renameField(field, newName); } private String getNextFieldName(BT_Field field) { while(true) { String newName = usedMethodNameGenerator.getName(); if(newName == null) { break; } if(!fieldNameIsUnavailable(field, newName)) { return newName; } } if(constantPoolNameGenerator != null) { constantPoolNameGenerator.reset(); if(!hasOutsideAccessors(field)) { while(true) { String result = constantPoolNameGenerator.getLongestName(); if(result == null) { break; } //if the field name is not available it should be removed because no other field can use it either //if it is available then we will use it so we should remove it in this case as well constantPoolNameGenerator.removeLast(); if(!fieldNameIsUnavailable(field, result)) { return result; } } } } while(true) { String result = nameGenerator.peekName(); if(!fieldNameIsUnavailable(field, result)) { String cpName = getShortestAvailableConstantPoolFieldName(field, result.length()); if(cpName != null) { result = cpName; } else { nameGenerator.getName(); } return result; } else { nameGenerator.getName(); } } } private String getShortestAvailableConstantPoolFieldName(BT_Field field, int maximumLength) { if(constantPoolNameGenerator == null) { return null; } while(true) { String result = constantPoolNameGenerator.getShortestName(); if(result == null || UTF8Converter.convertToUtf8(result).length > maximumLength) { return null; } //if the field name is not available it should be removed because no other field can use it either //if it is available then we will use it so we should remove it in this case as well constantPoolNameGenerator.removeLast(); if(!fieldNameIsUnavailable(field, result)) { //in this particular case we will end up checking availability a second time in the main //loop, so we could create a hack here to speed things up return result; } } } private boolean fieldNameIsUnavailable(BT_Field field, String name) { RelatedNameCollector collector = nameCollectorCreator.getRelatedNameCollector(field.getDeclaringClass()); if(collector.fieldNameAlreadyExists(name)) { return true; } return false; } private void renameField(BT_Field field, String name) { nameHandler.rename(field, name); nameHandler.freezeName(field); RelatedNameCollector collector = nameCollectorCreator.getRelatedNameCollector(field.getDeclaringClass()); collector.addFieldName(name); } private void renameFields() { if(constantPoolNameGenerator != null) { constantPoolNameGenerator.reset(); } usedMethodNameGenerator.reset(); nameGenerator.reset(); BT_FieldVector fields = clazz.getFields(); for(int i=0; i<fields.size(); i++) { BT_Field field = fields.elementAt(i); if(!nameHandler.nameIsFixed(field)) { renameField(field); } } } private String getNextMethodName(BT_Method method) { //we try to get a method name from the constant pool if the method is private or not-accessed from elsewhere if(constantPoolNameGenerator != null && !hasOutsideAccessors(method)) { constantPoolNameGenerator.reset(); while(true) { String result = constantPoolNameGenerator.getLongestName(); if(result == null) { break; } if(!methodNameIsUnavailable(method, result)) { //we don't add the name to the used list because //1) it is still available from the constant pool list, and //2) the name is potentially long so it should not be used by methods accessed from elsewhere return result; } } } //we try to overload an existing short name usedMethodNameGenerator.reset(); while(true) { String result = usedMethodNameGenerator.getName(); if(result == null) { break; } if(!methodNameIsUnavailable(method, result)) { return result; } } //now we try to use a previously generated name that was unusable, so that //we do not waste any short names unusedGeneratedMethodNames.reset(); while(true) { String result = unusedGeneratedMethodNames.getName(); if(result == null) { break; } if(!methodNameIsUnavailable(method, result)) { //is there something just as short in the constant pool? String cpName = getShortestAvailableConstantPoolMethodName(method, result.length()); if(cpName != null) { result = cpName; } else { unusedGeneratedMethodNames.removeLast(); } usedMethodNameGenerator.add(result); return result; } } //now we generate a new short name while(true) { String result = nameGenerator.peekName(); if(methodNameIsUnavailable(method, result)) { nameGenerator.getName(); unusedGeneratedMethodNames.add(result); } else { //is there something just as short in the constant pool? String cpName = getShortestAvailableConstantPoolMethodName(method, result.length()); if(cpName != null) { result = cpName; } else { nameGenerator.getName(); } usedMethodNameGenerator.add(result); return result; } } } private String getShortestAvailableConstantPoolMethodName(BT_Method method, int maximumLength) { if(constantPoolNameGenerator == null) { return null; } while(true) { String result = constantPoolNameGenerator.getShortestName(); if(result == null || UTF8Converter.convertToUtf8(result).length > maximumLength) { return null; } if(!methodNameIsUnavailable(method, result)) { return result; } } } private void renameMethod(BT_Method method) { String newName; if(prepend) { newName = '_' + method.getName(); while(methodNameIsUnavailable(method, newName)) { newName = '_' + newName; } } else { newName = getNextMethodName(method); } renameMethod(method, newName); } private void renameMethods() { nameGenerator.reset(); BT_MethodVector methods = clazz.getMethods(); for(int i=0; i<methods.size(); i++) { BT_Method method = methods.elementAt(i); if(!nameHandler.nameIsFixed(method)) { renameMethod(method); } } } void renameMembers() { //the order here is important because fields attempt to have the same names as methods. renameMethods(); renameFields(); } private boolean methodNameIsUnavailable(BT_Method methodToRename, String name) { Set checkedClasses = new HashSet(); BT_MethodVector relatedMethods = relatedMethodMap.getRelatedMethods(methodToRename); for(int j=0; j<relatedMethods.size(); j++) { BT_Method method = relatedMethods.elementAt(j); BT_Class mClass = method.getDeclaringClass(); if(checkedClasses.contains(mClass)) { continue; } checkedClasses.add(mClass); RelatedNameCollector collector = nameCollectorCreator.getRelatedNameCollector(mClass); if(collector.methodNameAlreadyExists(name, method.getSignature())) { return true; } } return false; } private void renameMethod(BT_Method methodToRename, String name) { BT_MethodVector relatedMethods = relatedMethodMap.getRelatedMethods(methodToRename); for(int j=0; j<relatedMethods.size(); j++) { BT_Method method = relatedMethods.elementAt(j); RelatedNameCollector collector = nameCollectorCreator.getRelatedNameCollector(method.getDeclaringClass()); nameHandler.rename(method, name); nameHandler.freezeName(method); collector.addMethodName(name, method.getSignature()); } } /** * @return true if the method is accessed from outside the declaring class */ public static boolean hasOutsideAccessors(BT_Method memberMethod) { if(!memberMethod.isPrivate()) { BT_MethodCallSiteVector accessors = memberMethod.callSites; if(accessors != null) { for (int k = 0; k < accessors.size(); k++) { BT_MethodCallSite accessor = accessors.elementAt(k); BT_Class accessorClass = accessor.getFrom().getDeclaringClass(); if (accessorClass != memberMethod.getDeclaringClass()) { return true; } } } } return false; } /** * @return true if the field is accessed from outside the declaring class */ public static boolean hasOutsideAccessors(BT_Field memberField) { if(!memberField.isPrivate()) { BT_AccessorVector accessors = memberField.accessors; if(accessors != null) { for (int k = 0; k < accessors.size(); k++) { BT_Accessor accessor = accessors.elementAt(k); BT_Class accessorClass = accessor.getFrom().getDeclaringClass(); if (accessorClass != memberField.getDeclaringClass()) { return true; } } } } return false; } }
package application; import application.blocks.*; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.*; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.File; import java.io.IOException; public class RootLayout extends AnchorPane { private Stage primaryStage; private FileChooser chooser; /** * FXML elements on RootLayout */ @FXML SplitPane base_pane; @FXML AnchorPane right_pane; @FXML private VBox left_pane; @FXML private Button save_button, load_button; private SchemeBlock mDragOverIcon = null; RootLayout(Stage primaryStage) { this.primaryStage = primaryStage; FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource("/views/RootLayout.fxml") ); fxmlLoader.setRoot(this); fxmlLoader.setController(this); this.chooser = new FileChooser(); try { fxmlLoader.load(); } catch (IOException exception) { throw new RuntimeException(exception); } } @FXML protected void showSaveFileChooser() { File file = this.chooser.showSaveDialog(primaryStage); } @FXML protected void showLoadFileChooser() { File file = this.chooser.showOpenDialog(primaryStage); } @FXML private void initialize() { this.save_button.setTooltip(new Tooltip("Save scheme")); this.load_button.setTooltip(new Tooltip("Load scheme")); //Add one icon that will be used for the drag-drop process //This is added as a child to the root AnchorPane so it can be //visible on both sides of the split pane. mDragOverIcon = new SchemeBlock(); mDragOverIcon.setVisible(false); mDragOverIcon.setOpacity(0.65); getChildren().add(mDragOverIcon); for (int i = 0; i < BlockTypes.values().length; i++) { SchemeBlock icn = new SchemeBlock(); switch (BlockTypes.values()[i]) { case plus: icn = new PlusBlock(); break; case minus: icn = new MinusBlock(); break; case mult: icn = new MultiplyBlock(); break; case div: icn = new DivideBlock(); break; default: break; } icn.setType(BlockTypes.values()[i]); left_pane.getChildren().add(icn); } } }
public class Factory { public static Fruit getFruit(String fruit) { if(fruit.equalsIgnoreCase("apple")) { return new Apple(); } else if(fruit.equalsIgnoreCase("banana")) { return new Banana(); } else { System.out.println("ÕÒ²»µ½¸ÃÀà"); return null; } } }
package de.jmda.core.mproc.task; import static de.jmda.core.util.StringUtil.sb; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.io.FileUtils; import de.jmda.core.util.Properties; public class SourceCodeProducer { private final static String DIR_SRC_ROOT_KEY = SourceCodeProducer.class.getName() + ".DIR_SRC_ROOT"; private final static String DIR_SRC_ROOT_DEFAULT = "tmp/src/model/java"; public final static String DIR_SRC_ROOT = Properties.get(DIR_SRC_ROOT_KEY, DIR_SRC_ROOT_DEFAULT); public static class PackageInfo { private String packageName; private Set<TypeInfo> typeInfos; /** directory for package with relative path */ private File directory; public PackageInfo(String packageName) { if (packageName == null) throw new IllegalArgumentException("packageName must not be null"); this.packageName = packageName; typeInfos = new HashSet<>(); directory = new File(packageName.replace('.', File.separatorChar)); } public String getPackageName() { return packageName; } public Set<TypeInfo> getTypeInfos() { return typeInfos; } /** @see #directory */ public File getDirectory() { return directory; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((packageName == null) ? 0 : packageName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PackageInfo other = (PackageInfo) obj; if (packageName == null) { if (other.packageName != null) return false; } else if (!packageName.equals(other.packageName)) return false; return true; } } public static class TypeInfo { private PackageInfo packageInfo; private String simpleTypeName; private String content; /** file for type with relative path */ private File file; public TypeInfo(PackageInfo packageInfo, String simpleTypeName, String content) { this.packageInfo = packageInfo; this.simpleTypeName = simpleTypeName; this.content = content; String directoryName = packageInfo.getDirectory().getPath(); String simpleName = simpleTypeName + ".java"; String qualifiedName = directoryName.isEmpty() ? simpleName : directoryName + File.separator + simpleName; file = new File(qualifiedName); packageInfo.getTypeInfos().add(this); } public PackageInfo getPackageInfo() { return packageInfo; } public String getSimpleTypeName() { return simpleTypeName; } public String getContent() { return content; } /** @see #file */ public File getFile() { return file; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((packageInfo == null) ? 0 : packageInfo.hashCode()); result = prime * result + ((simpleTypeName == null) ? 0 : simpleTypeName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TypeInfo other = (TypeInfo) obj; if (packageInfo == null) { if (other.packageInfo != null) return false; } else if (!packageInfo.equals(other.packageInfo)) return false; if (simpleTypeName == null) { if (other.simpleTypeName != null) return false; } else if (!simpleTypeName.equals(other.simpleTypeName)) return false; return true; } } private List<PackageInfo> packageInfos; public SourceCodeProducer() { packageInfos = new ArrayList<>(); } public SourceCodeProducer(List<PackageInfo> packageInfos) { this.packageInfos = packageInfos; } public List<PackageInfo> getPackageInfos() { return packageInfos; } public void produce() { produce(new File(DIR_SRC_ROOT)); } public void produce(File sourceRoot) { packageInfos.forEach(pi -> produce(sourceRoot, pi)); } private void produce(File sourceRoot, PackageInfo packageInfo) { packageInfo.getTypeInfos().forEach(ti -> produce(sourceRoot, ti)); } private void produce(File sourceRoot, TypeInfo typeInfo) { StringBuffer result = sb(); String packageName = typeInfo.getPackageInfo().getPackageName(); // shortcut if (packageName.isEmpty() == false) { result.append("package " + packageName + ";\n\n"); } result.append(typeInfo.getContent()); File file = new File(sourceRoot, typeInfo.getFile().getPath()); try { FileUtils.writeStringToFile(file, result.toString(), Charset.defaultCharset(), false); } catch (IOException e) { throw new RuntimeException("failure writing file " + file.getAbsolutePath(), e); } } }
package com.intramail.model; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotEmpty; public class User { @NotEmpty String name; @NotEmpty @Size(min=16,max=40) String email; @NotEmpty @Size(min=8,max=20) String password; @Size(max=40) String altemail; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAltemail() { return altemail; } public void setAltemail(String altemail) { this.altemail = altemail; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getPhno() { return phno; } public void setPhno(String phno) { this.phno = phno; } String sex; @NotEmpty String country; @Size(min=10, max=10) String phno; }
package assgn.JianKai; import assgn.Login; import java.text.SimpleDateFormat; import java.util.Calendar; import javax.swing.table.DefaultTableModel; import listLink.store; public class report extends javax.swing.JFrame { store save; public report() { initComponents(); } public report(store save) { this.save = save; this.setVisible(true); this.setLocationRelativeTo(null); Calendar now = Calendar.getInstance(); String themonth = new SimpleDateFormat("MMM").format(now.getTime()); String theyear = new SimpleDateFormat("YYYY").format(now.getTime()); this.setTitle("Report for Menu"); initComponents(); jLabel1.setText("Monthly Report : " +themonth + " "+theyear); displayMenu(); } public void displayMenu(){ DefaultTableModel model = (DefaultTableModel)jTable1.getModel(); Calendar now = Calendar.getInstance(); String themonth = new SimpleDateFormat("MMM").format(now.getTime()); String theyear = new SimpleDateFormat("YYYY").format(now.getTime()); Object [] row = new Object[4]; for(int i =1; i <= save.getMenu().getSize();i++){ if (save.getMenu().get(i).getthemonth().equals(themonth) && save.getMenu().get(i).gettheyear().equals(theyear)) { row[0] = save.getMenu().get(i).getAffID(); row[1]= save.getMenu().get(i).getFoodid(); row[2] = save.getMenu().get(i).getFoodname(); row[3] = save.getMenu().get(i).getPrice(); model.addRow(row); } } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); back = new javax.swing.JButton(); jButton1.setText("jButton1"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Affiliate ID", "Food ID", "Food Name", "Price" } )); jScrollPane1.setViewportView(jTable1); back.setText("Back"); back.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { backActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addComponent(back) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(back) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backActionPerformed this.setVisible(false); Manager red = new Manager(save); }//GEN-LAST:event_backActionPerformed /** * @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(report.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(report.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(report.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(report.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 report().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton back; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; // End of variables declaration//GEN-END:variables }
package lab3; public class HelloWorld { public static void main(String[] args) { int x=100; System.out.println("Hello, World !!!!\n"); System.out.println("\tชื่อ นางสาวพีรพร ขุนพิบูล"); System.out.println("รหัสนักศึกษา 362211760009"); System.out.println("สาขา การจัดการเทคโนโลยีสารสนเทศ"); System.out.println("คณะ เทคโนโลยีการจัดการ"); System.out.println("E-mail Phirapornkp@nvc.ac.th"); } }//class
package httf.ui; import httf.util.*; public class TextLine { public String text; public Bitmap[] chars; public int x; public int y; public TextLine(String text, int x, int y) { this.text = text; this.x = x; this.y = y; this.chars = new Bitmap[text.length()]; for(int i = 0; i < chars.length; i++) { String tex = "" + text.charAt(i); if(tex.equalsIgnoreCase("'")) tex = "ap"; else if(tex.equalsIgnoreCase(" ")) tex = "space"; else if(tex.equalsIgnoreCase("?")) tex = "qm"; else if(tex.equalsIgnoreCase(":")) tex = ".."; chars[i] = ResourceLoader.loadTexture("chars/char_" + tex.toLowerCase()); } } public void render(Bitmap root) { for(int i = 0; i < chars.length; i++) { root.draw(chars[i], x + (i * 8), y); } } }
package com.tutorial.basics.constants; enum Coffee { SMALL(1) , MEDIUM(2) , LARGE(3); private int value; private Coffee(int value) { this.value = value; } public int getValue(){ return this.value; } } public class PrintDays { public static void main(String[] args) { CoffeeShop.buyCoffee(Coffee.MEDIUM); } } class CoffeeShop{ public static void buyCoffee(Coffee size){ /*if(size == Coffee.SMALL) { System.out.println("Small"); }else if (size == Coffee.MEDIUM) { System.out.println("medium"); }else if(size == Coffee.LARGE) { System.out.println("Large"); }*/ if(size.getValue() == 1) { System.out.println("Small"); }else if (size.getValue() == 2) { System.out.println("medium"); }else if(size.getValue() == 3) { System.out.println("Large"); } } }
package com.ebupt.portal.canyon.common.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; /** * ehcache配置类 * * @author chy * @date 2019-03-15 10:22 */ @Configuration public class EhcacheConfig { @Value("${spring.cache.ehcache.config:config/ehcache.xml}") private String config; private static final String SPLIT = ":"; @Bean public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() { if (config.indexOf(SPLIT) >= 0) { config = config.split(":")[1]; } EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean(); ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource(config)); // 将EhCacheManager由单实例改成多实例 ehCacheManagerFactoryBean.setShared(true); return ehCacheManagerFactoryBean; } }
package com.designPattern.SOLID.srp.problem; public class BankService { public void debit(double amount) { // DEBIT ACCOUNT } public void credit(double amount) { // CREDIT ACCOUNT } public void printStatement() { // PRINT ACCOUNT STATEMENT } public void loanInterestInfo(double amount, String loanType) { if(loanType.equals("Car")) { // CAR LOAN } else if(loanType.equals("Home")) { // HOME LOAN } else if(loanType.equals("Personal")) { // PERSONAL LOAN } } public void sendOTP(String medium) { if(medium.equals("email")) { // SEND OTP ON EMAIL } else if(medium.equals("mobile")) { // SEND OTP ON MOBILE } } }
package com.giga.service; import com.giga.entity.Category; import com.giga.repository.ICategoryRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class CategoryService implements ICategoryService { @Autowired ICategoryRepository categoryRepository; @Override public List<Category> findAll() { return categoryRepository.findAll(); } }
package com.espendwise.ocean.common.emails; public interface EmailType { public String name(); }
package com.lay.android_plugin; import android.content.Context; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Environment; import android.util.DisplayMetrics; import android.util.Log; import java.io.File; import java.lang.reflect.Method; import dalvik.system.DexClassLoader; public class PluginManager { private static final String TAG = PluginManager.class.getSimpleName(); private Context mContext; private static PluginManager pluginManager; public PluginManager(Context context) { this.mContext = context; } public static PluginManager getInstance(Context context) { if (pluginManager == null) { synchronized (PluginManager.class) { if (pluginManager == null) { pluginManager = new PluginManager(context); } } } return null; } private Resources mResources; private DexClassLoader mDexClassLoader; /** * Activity dexclass * layout */ public void loadPlugin() { try { /** * 加载DexClass */ File file = new File(Environment.getExternalStorageDirectory() + File.separator + "host.apk"); if (!file.exists()) { Log.d(TAG, "插件包, 不存在!!!"); return; } String pluginPath = file.getAbsolutePath(); // dexClassLoader需要一个缓存目录 /data/data/当前应用的包名/pDir File fDir = mContext.getDir("pDir", Context.MODE_PRIVATE); String oDir = fDir.getAbsolutePath(); mDexClassLoader = new DexClassLoader(pluginPath, oDir, null, mDexClassLoader); /** * 加载layout */ AssetManager assetManager = AssetManager.class.newInstance(); // 我们要执行此方法,为了把插件包的路径 添加进去 Method addAssetPathMethod = assetManager.getClass().getMethod("addAssetPath", String.class); addAssetPathMethod.invoke(assetManager, pluginPath); Resources resources = mContext.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); Configuration config = resources.getConfiguration(); // 特殊的 Resources,加载插件里面的资源的 Resources mResources = new Resources(assetManager, metrics, config); } catch (Exception e) { e.printStackTrace(); } } public ClassLoader getClassLoader() { return mDexClassLoader; } public Resources getResources() { return mResources; } }
package cn.chinaunicom.monitor.beans; import java.util.List; /** * Created by yfyang on 2017/8/10. */ public class Center { //public List<CenterEntity> center; public List<CenterEntity> records; public int recordCount; }
package com.projet3.library_webservice.library_webservice_business.impl; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import com.projet3.library_webservice.library_webservice_business.interfaces.BookManager; import com.projet3.library_webservice.library_webservice_consumer.DAO.BookDAO; import com.projet3.library_webservice.library_webservice_consumer.DAO.BorrowingDAO; import com.projet3.library_webservice.library_webservice_consumer.DAO.UserDAO; import com.projet3.library_webservice.library_webservice_model.beans.Book; import com.projet3.library_webservice.library_webservice_model.beans.Borrowing; public class BookManagerImpl implements BookManager { @Autowired private BookDAO bookDAO; @Autowired private BorrowingDAO borrowingDAO; @Autowired private UserDAO userDAO; public Book getBook( int id ) throws SQLException { Book book = bookDAO.getBookById(id); return book; } @Override public List<Book> getBookList() throws SQLException { List<Book> bookList = bookDAO.getBookList(); return bookList; } @Override public List<Book> bookResearch(String title) throws SQLException { List<Book> bookFound = bookDAO.bookResearch(title); return bookFound; } @Override public void createBook(Book book) throws SQLException { // TODO Auto-generated method stub } @Override public List<Borrowing> getBorrowings(int userId) throws SQLException { List<Borrowing> borrowingList = borrowingDAO.getBorrowingByUser(userDAO.getUserById(userId)); return borrowingList; } @Override public void extendBorrowing(int bookId) throws SQLException { Borrowing borrowing = borrowingDAO.getBorrowingByBook(bookDAO.getBookById(bookId)); Date dateToUpdate = borrowing.getEndingDate(); Date now = new Date(); if ( now.before(dateToUpdate) ) { Calendar myCal = Calendar.getInstance(); myCal.setTime(dateToUpdate); myCal.add(Calendar.MONTH, +1); Date updatedDate = myCal.getTime(); borrowing.setEndingDate(updatedDate); borrowingDAO.updateBorrowing(borrowing); } } @Override public void deleteBorrowing(int bookId) throws SQLException { Borrowing borrowing = borrowingDAO.getBorrowingByBook(bookDAO.getBookById(bookId)); borrowingDAO.deleteBorrowing(borrowing); } @Override public Date getNextBookReturn(String bookTitle) throws SQLException { List<Book> bookList = bookDAO.getBookByTitle(bookTitle); List<Integer> idsList = bookList.stream().map( Book::getId).collect(Collectors.toList()); List<Borrowing> borrowingList = borrowingDAO.getBorrowingsById(idsList); return borrowingList.stream().map(u -> u.getEndingDate()).min(Date::compareTo).get(); } }
package lesson9; public class Lesson9 { public static void main(String[] args) { //hello(args); showMaxData(); sortData(); // 9-9 int[][] arr = { { 3, 1, 4, 1, }, { 5, 9, 2, }, { 6, 5, }, { 3, }, }; printTwoDimentionalArray(arr); } /** * 9-6 */ public static void hello(String[] args){ String[] message = {"おはよう!","こんにちは!","こんばんは!"}; if(args.length != 1){ System.out.println("使い方:java SelectGreeting 番号"); System.exit(0); } int num = Integer.parseInt(args[0]); if(0 <= num && num < message.length){ System.out.println(message[num]); }else{ System.out.println("番号は0~"+(message.length-1)+"の範囲で指定してください。"); } } /** * 9-7 */ public static void showMaxData(){ int[] data = {31,41,59,26,53,58,97,93,23,84}; int max_data = data[0]; for (int i = 1; i < data.length; i++){ max_data = max_data < data[i] ? data[i] : max_data; } System.out.println("最大値は"+max_data+"です。"); } /** * 9-8 */ public static void sortData(){ int[] data = {31,41,59,26,53,58,97,93,23,84}; int tmp = 0; System.out.println("並び替える前"); for (int i = 0; i < data.length; i++) System.out.print(data[i]+" "); System.out.println(""); //昇順で並び替え for (int i = 0; i < data.length; i++){ for (int j = i; j < data.length; j++){ if (data[j] < data[i]){ tmp = data[i]; data[i] = data[j]; data[j] = tmp; } } } System.out.println("並び替えた後"); for (int i = 0; i < data.length; i++) System.out.print(data[i]+" "); System.out.println(""); } /** * 9-9 */ public static void printTwoDimentionalArray(int[][] arr){ System.out.println("{"); for (int i = 0; i < arr.length; i++){ System.out.print(" {"); for (int j = 0; j < arr[i].length; j++){ System.out.printf("%2d,",arr[i][j]); } System.out.println(" },"); } System.out.print("},"); } }
package com.tencent.rtmp; import com.tencent.liteav.basic.util.a; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; class TXLivePusher$3 implements Runnable { final /* synthetic */ TXLivePusher this$0; final /* synthetic */ String val$videoFilePath; TXLivePusher$3(TXLivePusher tXLivePusher, String str) { this.this$0 = tXLivePusher; this.val$videoFilePath = str; } public void run() { File parentFile = new File(this.val$videoFilePath).getParentFile(); String format = new SimpleDateFormat("yyyyMMdd_HHmmssSSS").format(new Date(System.currentTimeMillis())); String str = parentFile + File.separator + String.format("TXUGCCover_%s.jpg", new Object[]{format}); a.a(this.val$videoFilePath, str); TXLivePusher.access$400(this.this$0, this.val$videoFilePath, str); } }
class InicialiacacaoErroCompilacao { public static void escopoVar() { /* * Não pode ter uma variavel com mesmo nome da variavel usada no for * antes do looping e nem depois do looping*/ //int i =0; for(int i =0;i<5;i++) { System.out.println(i); } //System.out.println(i); } public static void test() { char letra = 'c'; do { System.out.print(letra++); System.out.println("proxima" + letra); } while(letra <='f'); } public static void main(String... args) { // Códico não irá compila pois toda várivel dentro de método tem que ser inicializada // A variavel pode não ser inicializada, porém ela também não pode ser usada . String varNaoInicializada; char price; //System.out.println(varNaoInicializada); //System.out.println(price); test(); } }
package com.monkeyuser.testcases; import org.openqa.selenium.By; import org.testng.annotations.Test; import com.monkeyuser.base.TestBase; public class ComicsSpecificDates extends TestBase{ @Test public void SpecificDatesComics() { driver.findElement(By.xpath("//*[@id=\"list\"]")).click(); //Clicks 'Comic List' //December 4, 2018 driver.findElement(By.cssSelector("body > div.content-container > div.page > div > div > div:nth-child(47) > div > div > a.image-title")).click(); //June 19, 2018 driver.navigate().back(); driver.findElement(By.cssSelector("body > div.content-container > div.page > div > div > div:nth-child(67) > div > div > a.image-title")).click(); //May 30, 2017 driver.navigate().back(); driver.findElement(By.cssSelector("body > div.content-container > div.page > div > div > div:nth-child(117) > div > div > a.image-title")).click(); } }
package oicq.wlogin_sdk.a; public final class af extends a { public int vJA; public af() { this.vJA = 0; this.vIl = 323; } }
package Files; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class Ex1 { public static void main(String[] args) throws Exception { //FileInputStream fin = new FileInputStream("D://Mahesh.xlsx"); FileInputStream fin = new FileInputStream("D://Mahesh1.xlsx"); XSSFWorkbook xss = new XSSFWorkbook(fin); XSSFSheet sh = xss.getSheetAt(0); System.out.println(sh.getRow(0).getCell(0).getStringCellValue()); xss.close(); fin.close(); } }
import java.net.*; import javax.swing.*; /** * Klasa pozwala na sprawne przeprowadzanie meczu. Posiada pola dla serwera i klienta. * */ class ClientManager { public GameWindow gameWindow; ClientManager(GameWindow gameWindow) { this.gameWindow = gameWindow; makeBoard(); } Game boardGraphic; /** * Nasłuchuje klienta. */ ServerSocket s; /** * Umożliwia komunikację między klientem, a serwerem. */ Socket socket; /** * Metoda wykonuje ostatni ruch. * @param x współrzędna x * @param y współrzędna y */ void paintLastMove(int x, int y) { if (x == 100) { String a = "Player passed"; String b = "Game info"; JOptionPane.showMessageDialog(null, a, b, JOptionPane.INFORMATION_MESSAGE); } else if (x == 30 && y == 2) { double b = boardGraphic.getBlackScore(); double w = boardGraphic.getWhiteScore(); if (b > w) new ThreadForJOptionPane("Black", gameWindow.window); else new ThreadForJOptionPane("White", gameWindow.window); } else { gameWindow.jPanel2.lastX = y*25 + 20; gameWindow.jPanel2.lastY = x*25 + 24; gameWindow.jPanel2.repaint(); } } /** * Tworzy nową planszę */ private void makeBoard() { boardGraphic = new Game(19); } /** * Zwraca planszę * @return plansza */ Game getBoard() { return(boardGraphic); } }
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class Billiard extends JPanel implements Runnable{ int ui_width = 300, ui_height = 300; double oval_w = 10, oval_h = 10; double oval_cx, oval_cy; double x = ui_width / 2, y = ui_height / 2, dx = 1.618034 * 3, dy = 3; Thread my_thread = null; public Billiard(){ setPreferredSize(new Dimension(ui_width, ui_height)); startThread(); } public void startThread(){ if(my_thread == null){ my_thread = new Thread(this); my_thread.start(); } } public void stopThread(){ my_thread = null; } @Override public void run(){ Thread me = Thread.currentThread(); while(my_thread == me){ x += dx; y += dy; oval_cx = x + oval_w/2; oval_cx = y + oval_h/2; if((x + oval_w) > (double)ui_width || x < 0){ dx *= -1; } if((y + oval_h) > (double)ui_height || y < 0){ dy *= -1; } repaint(); try{ Thread.sleep(40); }catch(InterruptedException e){} } } @Override public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.GREEN); g.fillOval((int)x, (int)y, (int)oval_w, (int)oval_h); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("ビリヤード"); frame.add(new Billiard()); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }); } }
package com.utils.util.encrypt; public interface EnDecrpt { /** * 设置对称加密使用的密钥 * @param key */ public void setKey(byte[] key); /** * 设置非对称加密的公钥 * @param publicKeyBytes */ public void setPublicKey(byte[] publicKeyBytes); /** * 设置非对称加密的私钥 * @param privateKeyBytes */ public void setPrivateKey(byte[] privateKeyBytes); /** * 加密原始信息 * @param src * @return */ public byte[] encrypt(byte[] src); /** * 解析加密信息 * @param src * @return */ public byte[] decrypt(byte[] src); /** * 对内容进行签名,返回签名信息 * @param src * @return */ public byte[] sign(byte[] src); /** * 使用签名信息对原文进行验证,返回验证结果 * @param src 原文内容 * @param sign 签名内容 * @return */ public boolean check(byte[] src, byte[] sign); }
package pro.absolutne.lunchgator.integration.zomato; import com.jayway.jsonpath.JsonPath; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import pro.absolutne.lunchgator.data.entity.Location; import pro.absolutne.lunchgator.data.entity.MenuItem; import pro.absolutne.lunchgator.data.entity.Restaurant; import pro.absolutne.lunchgator.scraping.ScrapUtils; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import static java.util.stream.Collectors.toList; @SuppressWarnings("OptionalGetWithoutIsPresent") @Service public class ZomatoService { private static final Logger logger = LoggerFactory.getLogger(ZomatoService.class); private static final String API_ROOT = "https://developers.zomato.com/api/v2.1"; private static final HttpUrl urlRoot = HttpUrl.parse(API_ROOT); private static final String ROZHRANOVANY_KLIC = "26f285d8d3210d236d113e223850a017"; private final OkHttpClient client = new OkHttpClient(); private HttpUrl.Builder buildUrl(String path) { return urlRoot.newBuilder() .addPathSegment(path); } public List<MenuItem> getDishes(long restaurantId) { HttpUrl url = addRestaurantId(buildUrl("dailymenu"), restaurantId) .build(); List<Map<String, String>> d = JsonPath.parse(doRequest(url)) .read("$.daily_menus[0].daily_menu.dishes[*].dish"); return d.stream() .map(ZomatoService::toMenuItem) .collect(toList()); } public boolean hasDailyMenu(long restaurantId) { try { getDishes(restaurantId); } catch (Non200Exception e) { if (e.getMsg().toLowerCase() .contains("No Daily Menu".toLowerCase())) return false; else throw e; } return true; } public Restaurant getRestaurant(long id) { HttpUrl url = addRestaurantId(buildUrl("restaurant"), id) .build(); Map<String, Object> res = JsonPath.parse(doRequest(url)) .read("$"); return parseRestaurant(res); } private static Restaurant parseRestaurant(Map<String, Object> data) { String name = (String) data.get("name"); String resUrl = (String) data.get("url"); String id = (String) data.get("id"); Restaurant rest = new Restaurant(); rest.setLocation(parseLocation(data)); rest.setName(name); rest.setUrl(resUrl.split("\\?")[0]); // Remove query string (has just referrals) return rest; } public Collection<Restaurant> getRestaurantsByLocation(Location location, int radius) { logger.debug("Retrieving restaurants {} m around {} ", radius, location); HttpUrl url = buildUrl("search") .addQueryParameter("lat", location.getLatitude() + "") .addQueryParameter("long", location.getLongitude() + "") .addQueryParameter("radius", radius + "").build(); List<Map<String, Object>> res = JsonPath.parse(doRequest(url)) .read("$.restaurants[*].restaurant"); return res.stream() .map(ZomatoService::parseRestaurant) .collect(toList()); } private <T> Collection<T> collectAll(HttpUrl url) { Map<String, Object> res = JsonPath.parse(doRequest(url)).read("$"); long total = Long.parseLong((String) res.get("results_found")); long shown = Long.parseLong((String) res.get("results_shown")); long offset = Long.parseLong((String) res.get("results_start")); return null; } private HttpUrl.Builder setOffset(HttpUrl.Builder builder, int offset) { return builder.setQueryParameter("start", offset + ""); } private static Location parseLocation(Map<String, Object> res) { Map<String, String> locationRes = (Map<String, String>) res.get("location"); String addresss = locationRes.get("address"); double lat = Double.parseDouble(locationRes.get("latitude")); double longi = Double.parseDouble(locationRes.get("longitude")); return new Location(addresss, lat, longi); } private String doRequest(HttpUrl url) { Request req = buildRequest(url); try { logger.trace("Making request {}", req); Response res = client.newCall(req).execute(); logger.trace("Response is {}", res); if (res.code() != 200) { String msg = null; try { msg = JsonPath.parse(res.body().string()) .read("message"); } catch (Exception e) { logger.warn("Failed to retrieve 'message' from non 200 response"); } throw new Non200Exception(res.code(), msg); } return res.body().string(); } catch (IOException e) { throw new RuntimeException(e); } } private static HttpUrl.Builder addRestaurantId(HttpUrl.Builder urlBuilder, long id) { return urlBuilder.addQueryParameter("res_id", Long.toString(id)); } private static Request buildRequest(HttpUrl url) { return new Request.Builder() .header("user_key", ROZHRANOVANY_KLIC) .url(url) .build(); } private static MenuItem toMenuItem(Map<String, String> dish) { String name = dish.get("name"); String price = dish.get("price"); double priceVal = 0; if (!price.isEmpty()) priceVal = ScrapUtils.retrieveDecimal(price).get(); MenuItem item = new MenuItem(); item.setName(name); item.setPrice(priceVal); return item; } }
package testSuites; import drivers.DriverContext; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import testClases.Carrusel.AsignarVentaCase; import static drivers.DriverContext.setUp; import static reports.Report.finalAssert; public class AsignarVentaCliente { @BeforeMethod public void iniciarSession(){ setUp("emulator-5554","android","C:\\apk\\registroDeUsuarios.apk","emulator-5554",true); } @AfterMethod public void cerrarSession(){ DriverContext.quitDriver(); } @Test(priority = 1, description = "Asignar Venta a Cliente") public void test2(){ AsignarVentaCase asignarVentaCase = new AsignarVentaCase(); asignarVentaCase.flujoTest(); finalAssert(); } @Test(priority = 2, description = "Validación final del Test") public void validacion(){ AsignarVentaCase asignarVentaCase = new AsignarVentaCase(); asignarVentaCase.validacionTest(); finalAssert(); } }
package random.gba.loader; import java.util.Date; import java.util.HashMap; import java.util.Map; import fedata.gba.fe6.FE6Data; import fedata.gba.fe7.FE7Data; import fedata.gba.fe8.FE8Data; import fedata.general.FEBase; import fedata.general.FEBase.GameType; import io.FileHandler; import util.DebugPrinter; import util.Diff; import util.DiffCompiler; import util.FileReadHelper; import util.FreeSpaceManager; import util.HuffmanHelper; import util.WhyDoesJavaNotHaveThese; public class TextLoader { private FEBase.GameType gameType; private String[] allStrings; private HuffmanHelper huffman; private long textArrayOffset; private long treeAddress; private long rootAddress; private Map<Integer, String> replacementsWithCodes = new HashMap<Integer, String>(); public Boolean allowTextChanges = false; public TextLoader(FEBase.GameType gameType, FileHandler handler) { super(); this.gameType = gameType; Date start = new Date(); switch (gameType) { case FE6: { huffman = new HuffmanHelper(handler); allStrings = new String[FE6Data.NumberOfTextStrings + 1]; textArrayOffset = FileReadHelper.readAddress(handler, FE6Data.TextTablePointer); treeAddress = FileReadHelper.readAddress(handler, FE6Data.HuffmanTreeStart); rootAddress = FileReadHelper.readAddress(handler, FileReadHelper.readAddress(handler, FE6Data.HuffmanTreeEnd)); for (int i = 1; i <= FE6Data.NumberOfTextStrings; i++) { String decoded = huffman.sanitizeByteArrayIntoTextString(huffman.decodeTextAddressWithHuffmanTree( FileReadHelper.readAddress(handler, textArrayOffset + 4 * i), treeAddress, rootAddress), false, gameType); DebugPrinter.log(DebugPrinter.Key.TEXT_LOADING, "Decoded FE6 String for index 0x" + Integer.toHexString(i).toUpperCase()); DebugPrinter.log(DebugPrinter.Key.TEXT_LOADING, decoded); allStrings[i] = decoded; } break; } case FE7: { huffman = new HuffmanHelper(handler); allStrings = new String[FE7Data.NumberOfTextStrings]; textArrayOffset = FileReadHelper.readAddress(handler, FE7Data.TextTablePointer); treeAddress = FileReadHelper.readAddress(handler, FE7Data.HuffmanTreeStart); rootAddress = FileReadHelper.readAddress(handler, FileReadHelper.readAddress(handler, FE7Data.HuffmanTreeEnd)); for (int i = 0; i < FE7Data.NumberOfTextStrings; i++) { String decoded = huffman.sanitizeByteArrayIntoTextString(huffman.decodeTextAddressWithHuffmanTree( FileReadHelper.readAddress(handler, textArrayOffset + 4 * i), treeAddress, rootAddress), false, gameType); DebugPrinter.log(DebugPrinter.Key.TEXT_LOADING, "Decoded FE7 String for index 0x" + Integer.toHexString(i).toUpperCase()); DebugPrinter.log(DebugPrinter.Key.TEXT_LOADING, decoded); allStrings[i] = decoded; } break; } case FE8: { huffman = new HuffmanHelper(handler); allStrings = new String[FE8Data.NumberOfTextStrings + 1]; textArrayOffset = FileReadHelper.readAddress(handler, FE8Data.TextTablePointer); treeAddress = FileReadHelper.readAddress(handler, FE8Data.HuffmanTreeStart); rootAddress = FileReadHelper.readAddress(handler, FileReadHelper.readAddress(handler, FE8Data.HuffmanTreeEnd)); for (int i = 1; i <= FE8Data.NumberOfTextStrings; i++) { String decoded = huffman.sanitizeByteArrayIntoTextString(huffman.decodeTextAddressWithHuffmanTree( FileReadHelper.readAddress(handler, textArrayOffset + 4 * i), treeAddress, rootAddress), false, gameType); DebugPrinter.log(DebugPrinter.Key.TEXT_LOADING, "Loaded Text for index 0x" + Integer.toHexString(i) + ": " + decoded); allStrings[i] = decoded; } break; } default: break; } Date end = new Date(); DebugPrinter.log(DebugPrinter.Key.TEXT_LOADING, "Text Import took " + Long.toString(end.getTime() - start.getTime()) + "ms"); huffman.printCache(); } public int getStringCount() { return allStrings.length; } // Note that we save strings with codes and without codes in separate tables. // When fetching, specifying whether to strip codes determines which to pull from. // If a string with codes is set, retrieving the string without codes will NOT give the modified string // and vice versa. Instead, it will return the unchanged string. public String getStringAtIndex(int index, boolean stripCodes) { if (index > 0xFFFF) { return null; } String replacement = replacementsWithCodes.get(index); String result = replacement != null ? replacement : allStrings[index]; if (result == null) { return ""; } if (!stripCodes) { return result; } return result.replaceAll("\\[[^\\[]*\\]", ""); } public void setStringAtIndex(int index, String string) { if (allowTextChanges) { replacementsWithCodes.put(index, string); } } public HuffmanHelper getHuffman() { return huffman; } public void commitChanges(FreeSpaceManager freeSpace, DiffCompiler compiler) { if (!allowTextChanges) { return; } // Let replacements with codes override any replacements without codes, if both exist. for (int index : replacementsWithCodes.keySet()) { String replacementWithCodes = replacementsWithCodes.get(index); // FE6 has some junk entries (or at least they look like junk.) if (index >= 0x1D2 && index <= 0x1E7) { continue; } // TODO: If we ever need to encode FE6 names, the new translation patch has a few characters that need special attention, since some characters are special thinner versions. boolean useThin = false; // These are character names. Only "Gwendolyn" needs this treatment. if (index >= 0x7EC && index <= 0x8B5 && replacementWithCodes.contains("Gwendolyn")) { useThin = true; } // The only other strings that have this are the Binding Blade (whose name we don't change), and some epilogue titles, which we also don't change. byte[] newByteArray = gameType == GameType.FE6 ? huffman.encodeNonHuffmanString(replacementWithCodes, true, useThin) : huffman.encodeString(replacementWithCodes, true); long offset = freeSpace.setValue(newByteArray, "Text At Index 0x" + Integer.toHexString(index)); //if (gameType == GameType.FE6) { offset |= 0x80000000; } // Mark this as uncompressed. long pointer = textArrayOffset + 4 * index; byte[] addressBytes = WhyDoesJavaNotHaveThese.bytesFromAddress(offset); compiler.addDiff(new Diff(pointer, 4, addressBytes, null)); allStrings[index] = replacementWithCodes; // We can replace these now, since they both have codes on them. } } }
package SP20_simulator; import java.util.Arrays; import java.util.stream.IntStream; /* * 명령어에 대한 정보 저장 */ public class Instruction { ResourceManager rMgr; char[] objectCode; int opcode; String opName; int format; boolean nReg; boolean iReg; boolean xReg; boolean bReg; boolean pReg; boolean eReg; // 3형식, 4형식 때 사용 int disp; int ta; int val; // 2형식에 사용 int r1; int r2; public Instruction(int opcode,ResourceManager resourceManager) throws Exception{ rMgr = resourceManager; disp = ta = val = 0; r1 = r2 = 0; setOP(opcode); setFlag(); } // 명령어 이름을 얻어오는 함수 및 opcode를 저장 public void setOP(int opcode) throws Exception{ this.opcode = opcode&0xFC; // bit Masking : OPcode만 얻음 switch(this.opcode) { // COMPR일 경우 case 0xA0: this.opName = "COMPR"; this.format = 2; break; // TIXR일 경우 case 0xB8: this.opName = "TIXR"; format = 2; break; // CLEAR일 경우 case 0xB4: this.opName = "CLEAR"; format = 2; break; // STL일 경우 case 0x14: this.opName = "STL"; format = 3; break; //JSUB case 0x48: this.opName = "JSUB"; format = 3; break; //LDA case 0x00: this.opName = "LDA"; format = 3; break; //COMP case 0x28: this.opName = "COMP"; format = 3; break; //JEQ case 0x30: this.opName = "JEQ"; format = 3; break; //J case 0x3C: this.opName = "J"; format = 3; break; //STA case 0x0C: this.opName = "STA"; format = 3; break; //LDT case 0X74: this.opName = "LDT"; format = 3; break; //TD case 0XE0: this.opName = "TD"; format = 3; break; //RD case 0XD8: this.opName = "RD"; format = 3; break; //STCH case 0X54: this.opName = "STCH"; format = 3; break; //JLT case 0X38: this.opName = "JLT"; format = 3; break; //STX case 0X10: this.opName = "STX"; format = 3; break; //RSUB case 0X4C: this.opName = "RSUB"; format = 3; break; //LDCH case 0X50: this.opName = "LDCH"; format = 3; break; //WD case 0XDC: this.opName = "WD"; format = 3; break; default: throw new Exception(); } } public void setFlag() { int pc = rMgr.getRegister(8); if(this.format ==3) { objectCode = rMgr.getMemory(pc, 3); boolean e= (rMgr.byteToInt(objectCode) & 0x1000) != 0; //4형식일 경우 if(e) { objectCode = rMgr.getMemory(pc, 4); rMgr.setRegister(8, pc+4); pc += 4; } else { rMgr.setRegister(8, pc+3); pc += 3; } } else if(this.format==2) { objectCode = rMgr.getMemory(pc, 2); rMgr.setRegister(8, pc+2); pc += 2; r1 = (objectCode[1]&0xF0)>>4; r2 = (objectCode[1]&0x0F); rMgr.targetAddress = 0; return; } nReg = (objectCode[0] & 0x02) != 0; iReg = (objectCode[0] & 0x01) != 0; xReg = (objectCode[1] & 0x80) != 0; bReg = (objectCode[1] & 0x40) != 0; pReg = (objectCode[1] & 0x20) != 0; eReg = (objectCode[1] & 0x10) != 0; // disp 구하기 (e확인) // 4형식일 때 if(this.eReg) { disp = rMgr.byteToInt(Arrays.copyOfRange(objectCode, 1, 4)); disp = disp&0xFFFFF; ta = disp; } // 3형식 일 때 else { disp = rMgr.byteToInt(Arrays.copyOfRange(objectCode, 1, 3)); disp = disp&0xFFF; } // ta 구하기 (b,p,x 확인) if(this.bReg) { int base = rMgr.getRegister(3); ta = base + disp; } else if(this.pReg) { // PC일 때만 음수가 있다. if((disp&0x800)!= 0) { disp |= 0xfffff000; } ta = pc + disp; } else { ta = disp; } if(this.xReg) { ta += rMgr.getRegister(1); } rMgr.targetAddress = ta; // val 구하기(n,i 확인) // n = 1, i = 1 일 때 if(this.nReg && this.iReg) { char[] valMem = rMgr.getMemory(ta, 3); val = rMgr.byteToInt(valMem); } // n = 1, i = 0 일 때 else if(this.nReg) { char[] valMem = rMgr.getMemory(ta, 3); ta = rMgr.byteToInt(valMem); rMgr.targetAddress = ta; valMem = rMgr.getMemory(ta, 3); val = rMgr.byteToInt(valMem); } // n = 0, i = 1 일 때 else if(this.iReg) { val = ta; } } public int getFormat() { return format; } }
package com.dreamcatcher.plan.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dreamcatcher.factory.PlanActionFactory; import com.dreamcatcher.factory.SiteActionFactory; import com.dreamcatcher.plan.action.PlanMakeAction; import com.dreamcatcher.plan.action.PlanViewAction; import com.dreamcatcher.util.*; @WebServlet("/plan") public class PlanController extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { execute(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding(CharacterConstant.DEFAULT_CHAR); execute(request, response); } private void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String root = request.getContextPath(); String path = "/main"; String act = request.getParameter("act"); System.out.println("action = " + act); int page = NumberCheck.nullToOne(request.getParameter("page")); String searchMod = StringCheck.nullToBlank(request.getParameter("searchMode")); String searchWord = null; if(request.getMethod().equals("GET")) searchWord = Encoder.serverCharToDefaultChar(StringCheck.nullToBlank(request.getParameter("searchWord"))); else searchWord = StringCheck.nullToBlank(request.getParameter("searchWord")); String viewMode = Encoder.serverCharToDefaultChar(StringCheck.nullToBlank(request.getParameter("viewMode"))); String categoryMode = StringCheck.nullToBlank(request.getParameter("searchMode")); String queryString = "&page=" + page + "&searchMod=" + searchMod + "&searchWord=" + UrlEncoder.encode(searchWord)+"&viewMode="+viewMode+"&categoryMode="+categoryMode; if("registerMap".equals(act)) { PageMove.redirect(response, root + "/plan/planMapView.jsp"); } else if("getSitesForMap".equals(act)) { PlanActionFactory.getPlanMapViewAction().execute(request, response); } else if("moveToPlanPage".equals(act)) { String jsonString = request.getParameter("jsonString"); request.setAttribute("jsonString", jsonString); PageMove.forward(request,response, "/plan/planRegister.tiles"); } else if("autoCompleteInMap".equals(act)) { PlanActionFactory.getPlanAutoCompleteInMapAction().execute(request, response); } else if ("registerPlan".equals(act)) { path = PlanActionFactory.getPlanMakeAction().execute(request, response); PageMove.redirect(response, root + path); } else if("modifyMapStart".equals(act)) { path = PlanActionFactory.getRouteModifyStartAction().execute(request, response); PageMove.forward(request, response, path); } else if("modifyMapEnd".equals(act)) { PlanActionFactory.getRouteModifyEndAction().execute(request, response); path = PlanActionFactory.getPlanViewAction().execute(request, response); PageMove.forward(request, response, path); } else if ("viewModify".equals(act)) { path = PlanActionFactory.getPlanModifyViewAction().execute(request, response); PageMove.forward(request, response, path); } else if ("modifyPlan".equals(act)) { PlanActionFactory.getPlanModifyAction().execute(request, response); path = PlanActionFactory.getPlanViewAction().execute(request, response); PageMove.forward(request, response, path); } else if ("viewPlan".equals(act)) { path = PlanActionFactory.getPlanViewAction().execute(request, response); PageMove.forward(request, response, path); } else if ("deletePlan".equals(act)) { PlanActionFactory.getPlanDeleteAction().execute(request, response); PageMove.redirect(response, root + "/route?act=routeArticleList"+queryString); } else if ("likePlan".equals(act)) { PlanActionFactory.getplanLikeAction().execute(request, response); } else if ("disLikePlan".equals(act)) { PlanActionFactory.getplanDisLikeAction().execute(request, response); } else if ("getPlanLatlng".equals(act)) { PlanActionFactory.getPlanGetLatLngAction().execute(request, response); } else { PageMove.redirect(response, root + path); } } }
package com.pybeta.daymatter.ui; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import com.actionbarsherlock.app.SherlockPreferenceActivity; import com.pybeta.daymatter.R; import com.pybeta.daymatter.utils.UtilityHelper; import com.pybeta.util.ChangeLogDialog; import com.umeng.fb.UMFeedbackService; public class AboutActivity extends SherlockPreferenceActivity implements OnPreferenceClickListener { private Preference mAboutusPref = null; private Preference mFeedbackPref = null; private Preference mSharedPref = null; private Preference mFollowPref = null; private Preference mChangelogPref = null; @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.about_preferences); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.title_activity_about); mSharedPref = findPreference("share_preferences"); mFeedbackPref = findPreference("feedback_preferences"); mAboutusPref = findPreference("about_preference_version"); mChangelogPref = findPreference("about_preference_changelog"); mFollowPref = findPreference("about_preference_follow_content"); mSharedPref.setOnPreferenceClickListener(this); mFeedbackPref.setOnPreferenceClickListener(this); mChangelogPref.setOnPreferenceClickListener(this); mFollowPref.setOnPreferenceClickListener(this); updateAboutusPreferenceSummary(); } private void updateAboutusPreferenceSummary() { String formatSize = getResources().getString(R.string.aboutus_summary_preferences); mAboutusPref.setSummary(String.format(formatSize, UtilityHelper.getAppVersionName(this))); } @Override public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) { switch (item.getItemId()) { case android.R.id.home: { finish(); break; } default: break; } return super.onOptionsItemSelected(item); } @Override public boolean onPreferenceClick(Preference preference) { if (preference.getKey().equals(mFeedbackPref.getKey())) { UMFeedbackService.openUmengFeedbackSDK(this); } else if (preference.getKey().equals(mSharedPref.getKey())) { UtilityHelper.share(this, getString(R.string.share_intent_subject), getString(R.string.share_intent_text), null); } else if (preference.getKey().equals(mChangelogPref.getKey())) { ChangeLogDialog _ChangelogDialog = new ChangeLogDialog(this); _ChangelogDialog.show(); } else if (preference.getKey().equals(mFollowPref.getKey())) { UtilityHelper.follow(this, getString(R.string.website)); } return false; } }
package com.wuxg.docs; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import org.wltea.analyzer.lucene.IKAnalyzer; /** * @author wuxianguang * es文档对象 */ @Document(indexName = "wu_test",type = "product") public class ProductDoc { @Id private Long id; /** * 整合的name字段,包括商品名称,品牌名称,商品类型 */ @Field(type = FieldType.Text,analyzer = "ik_max_word") private String name; @Field(type = FieldType.Long) private Long price; @Field(type = FieldType.Keyword) private String desc; @Field(index = false, type = FieldType.Keyword) private String imgUrl; }
package com.ifli.mbcp.dao.hibernate; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.ifli.mbcp.dao.LeadDAO; import com.ifli.mbcp.dao.exceptions.DAOException; import com.ifli.mbcp.domain.Lead; import com.ifli.mbcp.util.MBCPConstants; import com.ifli.mbcp.util.MBCPConstants.Lifecycle; import com.ifli.mbcp.util.MBCPConstants.PageType; import com.ifli.mbcp.util.MBCPConstants.SearchBy; import com.ifli.mbcp.util.MBCPUtil; import com.ifli.mbcp.vo.SearchCriteriaBean; import com.liferay.portal.kernel.util.StringPool; /** * Class responsible for performing operations specific to Lead Entity * * @author Niranjan * @since 6 May 2013 * @version 1.0 */ @Repository("leadDAO") @Transactional public class LeadDAOImpl extends GenericDAOImpl<Lead> implements LeadDAO { public LeadDAOImpl() { } /** * Returns a list of Lead instances whose First name or Last name starts * with the given value or an empty list if no results found * * @param value * search lead by this value * * @return list of Lead instances matching the give search criteria or empty * list if no results found */ @SuppressWarnings({ "unchecked", "rawtypes" }) public List<Lead> findByFirstOrLastName(final String value) { List<Lead> list = null; try { final String queryString = "from Lead as lead where lead.leadCustomerDetails.firstName like '" + value + "%' or lead.leadCustomerDetails.lastName like '" + value + "%'"; HibernateCallback hc = new HibernateCallback() { public List<Lead> doInHibernate(Session session) throws HibernateException, SQLException { return session.createQuery(queryString).list(); } }; list = (List<Lead>) hibernateTemplate.execute(hc); } catch (RuntimeException re) { throw re; } return list; } /** * Generic search method which returns the Leads matching the given search * criteria. The value field can be parsed to its respective expected type * without fearing the Cast exceptions because the value field for * corresponding search criteria is already been validated in * LeadSearchValidator * * @param searchCriteria * search criteria * @return list of Lead instances matching the given search criteria or * empty list if results not found or null for any unsupported * searchBy clause */ @SuppressWarnings({ "unchecked", "rawtypes" }) public List<Lead> search(final SearchCriteriaBean searchCriteria) { boolean includeLifecycleInWhereClause = true; int searchBy = searchCriteria.getSearchById(); String value = searchCriteria.getSearchText(); // Create the main Criteria final DetachedCriteria leadCriteria = DetachedCriteria.forClass(Lead.class); // Restriction to Search Individual or Group Lead leadCriteria.createAlias("kindOfLead", "kol").add(Restrictions.eq("kol.name", searchCriteria.getLeadType())); if (searchBy == SearchBy.LEAD_ID.getValue()) { leadCriteria.add(Restrictions.eq("leadId", Long.valueOf(value))); } else if (searchBy == SearchBy.PRODUCT.getValue()) { /* TODO For Performance improvement only: This is selecting all the non-sense in the world along with what we are interested in, check if can be fine tuned */ leadCriteria.createAlias("proposalsMade", "p",CriteriaSpecification.INNER_JOIN) .createAlias("p.insuranceProduct", "ip") .add(Restrictions.eq("ip.name", value)); /* String hql = "select lead from Lead lead join fetch lead.proposalsMade p where p.insuranceProduct.name = ?"; return hibernateTemplate.find(hql, value); */ } else if (searchBy == SearchBy.FIRST_OR_LAST_NAME.getValue()) { leadCriteria.createAlias("leadCustomerDetails", "lcd").add( Restrictions.or(Restrictions.like("lcd.firstName", value + StringPool.PERCENT), Restrictions.like("lcd.lastName", value + StringPool.PERCENT))); } else if (searchBy == SearchBy.LEAD_STATUS.getValue()) { leadCriteria.createAlias("leadStatus", "ls").add(Restrictions.eq("ls.name", value)); } else if (searchBy == SearchBy.MOBILE_NO.getValue()) { leadCriteria.createAlias("leadCustomerDetails", "lcd").add(Restrictions.eq("lcd.mobileNumber", value)); } else if (searchBy == SearchBy.LEAD_CREATED_DATE.getValue()) { try { Date date = new SimpleDateFormat(MBCPConstants.LEAD_DATE_FORMAT).parse(value); leadCriteria.add(Restrictions.between("createdDate", MBCPUtil.getLeadingDate(date), MBCPUtil.getTrailingDate(date))); } catch (ParseException e) { throw new RuntimeException("Incorrect Date Format : " + value); } } else if (searchBy == SearchBy.PENDING_STAGE.getValue()) { includeLifecycleInWhereClause = false; leadCriteria.add(Restrictions.eq("lifecycleState", Short.valueOf(value))); } else { /* * If you are here then we have a search criteria which we cant * handle, someone broke into our site or Intercepting and injecting * wrong Search Criteria knowing we can handle that. To the hacker : * Poor kid, we cant handle ur query but can break ourselves!! */ throw new DAOException("Invalid Search Criteria"); } /* * Impose an implicit restriction on Lifecycle if search itself is not * on Lifecycle State i.e, PENDING_STAGE. Fetch all the Leads whose * lifecyclestate corresponds to the PageType when the search is * performed on a page other than Lead */ if (includeLifecycleInWhereClause && searchCriteria.getPageType() != PageType.LEAD) { leadCriteria.add(Restrictions.eq("lifecycleState", Lifecycle.getLifecycleByState((short) searchCriteria.getPageType()).getValue())); } // Now that we have framed the search criteria Its time to run the query // on Executable Criteria List<Lead> list = null; try { HibernateCallback hc = new HibernateCallback() { public List<Lead> doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = leadCriteria.getExecutableCriteria(session); // setFetchSize and setFirstResult will come handy when u // introduce pagination for search results if (searchCriteria.getFetchSize() > -1) { criteria.setFetchSize(searchCriteria.getFetchSize()); } if (searchCriteria.getStart() > -1) { criteria.setFirstResult(searchCriteria.getStart()); } return criteria.list(); } }; list = (List<Lead>) hibernateTemplate.execute(hc); } catch (RuntimeException re) { throw re; } return list; } /* * Previous public List<Lead> search(SearchCriteriaBean searchCriteria) { * * int searchBy = searchCriteria.getSearchById(); String value = * searchCriteria.getSearchText(); * * if (searchBy == SearchBy.LEAD_ID.getValue()) { * * return findByProperty(Lead.class, "leadId", Long.valueOf(value)); * * } * * else if (searchBy == SearchBy.PRODUCT.getValue()) { * * String hql = * "select lead from Lead lead join fetch lead.proposalsMade p where p.insuranceProduct.name = ?" * ; * * return hibernateTemplate.find(hql, value); * * } else if (searchBy == SearchBy.FIRST_OR_LAST_NAME.getValue()) { * * return findByFirstOrLastName(value); * * } else if (searchBy == SearchBy.LEAD_STATUS.getValue()) { * * return findByProperty(Lead.class, "leadStatus.name", value); * * } else if (searchBy == SearchBy.MOBILE_NO.getValue()) { * * return findByProperty(Lead.class, "leadCustomerDetails.mobileNumber", * value); * * } else if (searchBy == SearchBy.LEAD_CREATED_DATE.getValue()) { * * try { return findByDateIgnoringTS(Lead.class, "createdDate", new * SimpleDateFormat(MBCPConstants.LEAD_DATE_FORMAT).parse(value)); } catch * (ParseException e) { throw new * RuntimeException("Incorrect Date Format : " + value); } * * } else if (searchBy == SearchBy.PENDING_STAGE.getValue()) { return * findByProperty(Lead.class, "lifecycleState", Short.valueOf(value)); * * } * * return null; } */ }
/* * [y] hybris Platform * * Copyright (c) 2000-2016 SAP SE * All rights reserved. * * This software is the confidential and proprietary information of SAP * Hybris ("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 Hybris. */ package com.cnk.travelogix.operations.order.converters.populator; import de.hybris.platform.converters.Populator; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import de.hybris.platform.servicelayer.dto.converter.Converter; import org.springframework.util.Assert; import com.cnk.travelogix.common.core.cart.data.FlightTravellerData; import com.cnk.travelogix.common.core.cart.data.TravellerData; import com.cnk.travelogix.common.core.model.FlightTravellerModel; import com.cnk.travelogix.common.core.model.TravellerModel; /** * This populator is used for populate FlightTravellerModel into FlightTravellerData * * @author C5244544 */ public class FlightTravellerPopulator implements Populator<FlightTravellerModel, FlightTravellerData> { private Converter<TravellerModel, TravellerData> travellerConverter; @Override public void populate(final FlightTravellerModel source, final FlightTravellerData target) throws ConversionException { Assert.notNull(source, "Parameter source cannot be null."); Assert.notNull(target, "Parameter target cannot be null."); target.setSpecialrequest(source.getSpecialRequest()); travellerConverter.convert(source,target); } /** * @return the travellerConverter */ public Converter<TravellerModel, TravellerData> getTravellerConverter() { return travellerConverter; } /** * @param travellerConverter * the travellerConverter to set */ public void setTravellerConverter(final Converter<TravellerModel, TravellerData> travellerConverter) { this.travellerConverter = travellerConverter; } }
package graph; import java.util.ArrayList; /**************************************************************** * * @author Grupo 11 * * @param <T> * @param <E> * ***************************************************************/ public interface GraphInterface<T,E>{ /*********************************************************** * * @return Array de Nodes **********************************************************/ public ArrayList<Vertex<T, E>> getG(); /********************************************************** * * @param label * @return um node *********************************************************/ public Vertex<T,E> GetVertex(T label); /********************************************************* * * @param label -- adiciona um node * @return ********************************************************/ public boolean addVertex(T label); /******************************************************** * Adiciona uma aresta considerando dois nodes e o peso * entre si. * @param label1 -- node * @param label2 -- node vizinho * @param weight -- peso entre o node e o vizinho * * @return um array de Edge *******************************************************/ public boolean addE(T label1,T label2, E weight); public ArrayList<Edge<T,E>> GetEdgeVector(T label); }
package com.tencent.mm.plugin.remittance.ui; import android.view.View; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import com.tencent.mm.plugin.wxpay.a.f; import com.tencent.mm.sdk.platformtools.BackwardSupportUtil.b; import com.tenpay.android.wechat.TenpaySecureEditText; class RemittanceBusiUI$a { private View gYR; private float mBB; private float mBC; private float mBD; private TenpaySecureEditText mBE; private TextView mBF; private View mBG; final /* synthetic */ RemittanceBusiUI mBt; RemittanceBusiUI$a(RemittanceBusiUI remittanceBusiUI, int i, int i2, float f) { this.mBt = remittanceBusiUI; this.mBB = (float) i; this.mBC = (float) i2; this.mBD = f; } final void update() { RemittanceBusiUI.b(this.mBt).setTextSize(1, RemittanceBusiUI.a(this.mBt).mBC); RemittanceBusiUI.c(this.mBt).setTextSize(1, RemittanceBusiUI.a(this.mBt).mBB); if (this.mBF == null) { this.mBF = (TextView) RemittanceBusiUI.d(this.mBt).findViewById(f.wallet_title); } if (this.mBF != null) { this.mBF.setTextSize(this.mBB); } if (this.mBE == null) { this.mBE = (TenpaySecureEditText) RemittanceBusiUI.d(this.mBt).findViewById(f.wallet_content); } if (this.mBE != null) { this.mBE.setTextSize(this.mBC); } if (this.gYR == null) { this.gYR = this.mBE.findViewById(f.money_et_layout); } if (this.gYR != null) { this.gYR.setMinimumHeight(b.b(this.mBt, RemittanceBusiUI.a(this.mBt).mBC)); } if (this.mBG == null) { this.mBG = this.mBt.findViewById(f.walletformline); } if (this.mBG != null) { ((LayoutParams) this.mBG.getLayoutParams()).topMargin = b.b(this.mBt, this.mBD); } } }
package replicatorg.machine.model; import javax.swing.Box; public class ExclusionBox extends Box { public ExclusionBox(int arg0) { super(arg0); // TODO Auto-generated constructor stub } }
package pl.ark.chr.buginator.aggregator.domain; import pl.ark.chr.buginator.domain.BaseEntity; import pl.ark.chr.buginator.domain.core.Error; import javax.persistence.*; import java.time.LocalDateTime; import java.util.Objects; /** * Stores logs of statuses for communication with external platforms. */ @Entity @Table(name = "buginator_aggregator_log", indexes = { @Index(name = "aggregator_index", columnList = "aggregator_id"), @Index(name = "timestamp_index", columnList = "timestamp") }) public class AggregatorLog extends BaseEntity<AggregatorLog> { private static final long serialVersionUID = -6299139410461999506L; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "aggregator_id", nullable = false) private Aggregator aggregator; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "error_id", nullable = false) private Error error; @Column(name = "timestamp") private LocalDateTime timestamp; @Enumerated(EnumType.STRING) @Column(name = "status") private AggregatorLogStatus status; @Column(name = "error_description", length = 250) private String errorDescription; @Column(name = "retry_count") private int retryCount; protected AggregatorLog() { } private AggregatorLog(Builder builder) { setAggregator(builder.aggregator); setError(builder.error); setTimestamp(builder.timestamp); setStatus(builder.status); setErrorDescription(builder.errorDescription); } public Aggregator getAggregator() { return aggregator; } protected void setAggregator(Aggregator aggregator) { this.aggregator = aggregator; } public Error getError() { return error; } public void setError(Error error) { this.error = error; } public LocalDateTime getTimestamp() { return timestamp; } protected void setTimestamp(LocalDateTime timestamp) { this.timestamp = timestamp; } public void updateTimestamp() { this.timestamp = LocalDateTime.now(); } public AggregatorLogStatus getStatus() { return status; } public void setStatus(AggregatorLogStatus status) { this.status = status; } public String getErrorDescription() { return errorDescription; } public void setErrorDescription(String errorDescription) { this.errorDescription = errorDescription; } public void emptyErrorDescription() { this.error = null; } public int getRetryCount() { return retryCount; } protected void setRetryCount(int retryCount) { this.retryCount = retryCount; } public void incrementRetryCount() { this.retryCount += 1; } public static final class Builder { private Aggregator aggregator; private Error error; private LocalDateTime timestamp; private AggregatorLogStatus status; private String errorDescription; public Builder() { timestamp = LocalDateTime.now(); } public Builder aggregator(Aggregator val) { Objects.requireNonNull(val); aggregator = val; return this; } public Builder error(Error val) { Objects.requireNonNull(val); error = val; return this; } public Builder status(AggregatorLogStatus val) { status = val; return this; } public Builder errorDescription(String val) { errorDescription = val; return this; } public AggregatorLog build() { return new AggregatorLog(this); } } }
package com.parsermicroservice.parser.Controller; import com.parsermicroservice.parser.Exceptions.ParserException; import com.parsermicroservice.parser.Parser.Parser; import com.parsermicroservice.parser.Repository.ParserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.logging.Logger; @RestController @CrossOrigin @RequestMapping("/parser") public class ParserController { Logger myLogger = Logger.getLogger(String.valueOf(ParserController.class)); @Autowired private ParserRepository myParserRepository; @Autowired private static CriteriaBuilder myCriteria; @Autowired private static CriteriaQuery myCriteriaQuery; @Autowired private static EntityManager myEntityManager; @Autowired private static Page myPage; @GetMapping("/list") public List<Parser> listParserData(){ return myParserRepository.findAll(); } @GetMapping("/get/{id}") public Parser getParseById(@PathVariable Long id) throws ParserException { return myParserRepository.findById(id).orElseThrow(() -> new ParserException("Item Not Found!")); } @PostMapping("/new") public Parser createParse(@RequestBody Parser myParserModel){ return myParserRepository.save(myParserModel); } @PutMapping("/update/{id}") public Parser updateParse(@RequestBody Parser myParserModel, @PathVariable Long id){ return myParserRepository.findById(id).map((parserModel) ->{ parserModel.setLogDateTime(myParserModel.getLogDateTime()); parserModel.setLogMessage(myParserModel.getLogMessage()); return myParserRepository.save(parserModel); }).orElseGet(() ->{ myParserModel.setParserID(id); return myParserRepository.save(myParserModel); }); } @PostMapping("/file/upload") public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file) throws ParserException { try { String fileDirectory = ""; File myFile = new File(fileDirectory+file.getOriginalFilename()); myFile.createNewFile(); FileOutputStream myFileOutputStream = new FileOutputStream(myFile); myFileOutputStream.write(file.getBytes()); myFileOutputStream.close(); FileReader myReader = new FileReader(myFile); myReader.read(); myReader.close(); return new ResponseEntity<Object>("The File was uploaded Successfully!", HttpStatus.ACCEPTED); }catch(Exception ex){ throw new ParserException("Error:" + ex); } } @PostMapping("/search") public List<Parser> searchParsedData(@RequestBody Parser parsedDataQuery){ return myParserRepository.findAll(Example.of(parsedDataQuery)); } @DeleteMapping("/delete/{id}") public void deleteParse(@PathVariable Long id){ myParserRepository.deleteById(id); } @GetMapping("/count") public long getNoOfParsedData(){ return myParserRepository.count(); } }
package com.hesoyam.pharmacy.pharmacy.model; public enum OrderStatus { CREATED, ACCEPTED }
package main; public class TaillesdiffException extends Exception { }
package com.glory.recyclerviewwithcheckbox; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class TeacherAdapter extends RecyclerView.Adapter <TeacherAdapter.TeacherVieHolder> implements Filterable { List<TeachersModel> teachersModels ; List<TeachersModel> teacherIsCheck = new ArrayList<>(); List<TeachersModel> teacherIsFull; private boolean [] checkstate; private Context mContext; private setOnItemClickListener mListener; @NonNull @Override public TeacherVieHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.model, parent, false); return new TeacherVieHolder(view); } public TeacherAdapter(Context context, List<TeachersModel> teachersModels) { this.teachersModels = teachersModels; this.mContext = context; teacherIsFull = new ArrayList<>(); checkstate = new boolean[teachersModels.size()]; } public void updateList(ArrayList<TeachersModel> newList) { teachersModels = new ArrayList<>(); teachersModels.addAll(newList); notifyDataSetChanged(); } // Interface to implement click on the checkbox public interface setOnItemClickListener{ void onCheckboxClick(int position); } public void setOnItemClickListener(setOnItemClickListener listener){ this.mListener = listener; } @Override public void onBindViewHolder(@NonNull final TeacherVieHolder holder, final int position) { TeachersModel currentItem = teachersModels.get(position); int profile = currentItem.getProfilePix(); String name = currentItem.getName(); String mDescription = currentItem.getDescription(); // boolean mIscheck = currentItem.isChecked(); holder.profilePix.setImageResource(profile); holder.name.setText(name); holder.description.setText(mDescription); // holder.ischeck.setChecked(mIscheck); holder.more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popupMenu = new PopupMenu(mContext, holder.more); popupMenu.inflate(R.menu.options_menu); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()){ case R.id.edit: Toast.makeText(mContext, "Edit clicked", Toast.LENGTH_SHORT).show(); break; case R.id.delete: Toast.makeText(mContext, "delete clicked", Toast.LENGTH_SHORT).show(); break; case R.id.disable: Toast.makeText(mContext, "disabled clicked", Toast.LENGTH_SHORT).show(); break; } return false; } }); popupMenu.show(); } }); holder.ischeck.setChecked(false); if(checkstate[position]){ holder.ischeck.setChecked(true); }else { holder.ischeck.setChecked(false); } holder.ischeck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ checkstate[position] = false; }else{ checkstate[position] = true; } } }); } @Override public int getItemCount() { return teachersModels.size(); } public class TeacherVieHolder extends RecyclerView.ViewHolder{ private ImageView profilePix; private TextView name; private TextView description; private CheckBox ischeck; private ImageView more; public TeacherVieHolder(@NonNull final View itemView) { super(itemView); profilePix = itemView.findViewById(R.id.teacherImageview); name = itemView.findViewById(R.id.teacherName); description = itemView.findViewById(R.id.description); ischeck = itemView.findViewById(R.id.checkbox); more = itemView.findViewById(R.id.more); /* ischeck.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mListener != null){ int position = getAdapterPosition(); if(position != RecyclerView.NO_POSITION){ mListener.onCheckboxClick(position); } if (ischeck.isChecked()){ teacherIsCheck.add(teachersModels.get(position)); }else if (!ischeck.isChecked()){ teacherIsCheck.remove(teachersModels.get(position)); } } } }); */ itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { int position = getAdapterPosition(); if (mListener != null) { if (position != RecyclerView.NO_POSITION) { mListener.onCheckboxClick(position); } if (ischeck.isChecked()) { teacherIsCheck.add(teachersModels.get(position)); } else if (!ischeck.isChecked()) { teacherIsCheck.remove(teachersModels.get(position)); } if (ischeck != null) { ischeck.setChecked(true); if (ischeck.isChecked()) { ischeck.setVisibility(View.VISIBLE); } } } return true; } }); } } //Implementing search in recyclerview @Override public Filter getFilter() { return exampleFilter; } private Filter exampleFilter; { exampleFilter = new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { List<TeachersModel> filteredList = new ArrayList<>(); if (constraint == null || constraint.length() == 0) { filteredList.addAll(teacherIsFull); } else { String filteredPattern = constraint.toString().toLowerCase().trim(); for (TeachersModel item : teacherIsFull) { if (item.getName().toLowerCase().contains(filteredPattern)) { filteredList.add(item); } else if (item.getDescription().toLowerCase().contains(filteredPattern)) { filteredList.add(item); } } } FilterResults results = new FilterResults(); results.values = filteredList; return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { teachersModels.clear(); teacherIsCheck.addAll((List) results.values); notifyDataSetChanged(); } }; } }
package com.rsm.yuri.projecttaxilivre.chat.di; import com.rsm.yuri.projecttaxilivre.TaxiLivreAppModule; import com.rsm.yuri.projecttaxilivre.chat.ui.ChatActivity; import com.rsm.yuri.projecttaxilivre.domain.di.DomainModule; import com.rsm.yuri.projecttaxilivre.lib.di.LibsModule; import javax.inject.Singleton; import dagger.Component; /** * Created by yuri_ on 13/01/2018. */ @Singleton @Component(modules = {ChatModule.class, DomainModule.class, LibsModule.class, TaxiLivreAppModule.class}) public interface ChatComponet { void inject(ChatActivity activity); }
package tddd24.ajgallery.client; import java.util.ArrayList; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; @RemoteServiceRelativePath("stockPrices") public interface ajGalleryService extends RemoteService { ArrayList<String[]> processInput(String symbols); ArrayList<String[]> getData(); void deleteRow (String ID); }
package com.thread.imp.examples; import java.util.concurrent.Callable; public class AvgThread implements Callable<Integer> { public Integer maxEle = 0; public Integer sum = 0; @Override public Integer call() throws Exception { return sum/maxEle; } }
package pro.eddiecache.utils.discovery; import java.io.Serializable; import java.util.ArrayList; public class DiscoveredService implements Serializable { private static final long serialVersionUID = 1L; private ArrayList<String> cacheNames; private String serviceAddress; private int servicePort; private long lastHearTime = 0; public void setCacheNames(ArrayList<String> cacheNames) { this.cacheNames = cacheNames; } public ArrayList<String> getCacheNames() { return cacheNames; } public void setServiceAddress(String serviceAddress) { this.serviceAddress = serviceAddress; } public String getServiceAddress() { return serviceAddress; } public void setServicePort(int servicePort) { this.servicePort = servicePort; } public int getServicePort() { return servicePort; } public void setLastHearTime(long lastHearTime) { this.lastHearTime = lastHearTime; } public long getLastHearTime() { return lastHearTime; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((serviceAddress == null) ? 0 : serviceAddress.hashCode()); result = prime * result + servicePort; return result; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } if (!(o instanceof DiscoveredService)) { return false; } DiscoveredService other = (DiscoveredService) o; if (serviceAddress == null) { if (other.serviceAddress != null) { return false; } } else if (!serviceAddress.equals(other.serviceAddress)) { return false; } if (servicePort != other.servicePort) { return false; } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\n DiscoveredService"); sb.append("\n CacheNames = [" + getCacheNames() + "]"); sb.append("\n ServiceAddress = [" + getServiceAddress() + "]"); sb.append("\n ServicePort = [" + getServicePort() + "]"); sb.append("\n LastHearTime = [" + getLastHearTime() + "]"); return sb.toString(); } }
package restricao; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToMany; import javax.persistence.Table; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.NotEmpty; @Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "RES_TBPESSOA") @EqualsAndHashCode(exclude={"veiculos"}) public class ResPessoa { public static final Integer PESSOA_JURIDICA = 1; public static final Integer PESSOA_FISICA = 2; @Id @GeneratedValue @Column(name="PESSOA_ID", nullable=false) private @Getter @Setter Long id; @Column(name="TIPO_PESSOA") private @Getter @Setter Integer tipoPessoa; @NotEmpty(message = "O nome/raz„o social deve ser informado.") private @Getter @Setter String nome; @OneToMany private @Getter @Setter List<ResPessoaVeiculo> veiculos = new ArrayList<ResPessoaVeiculo>(0); }
package kr.pe.ssun.bark; import android.support.annotation.NonNull; import android.support.v4.app.FragmentActivity; import com.facebook.AccessToken; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.remoteconfig.FirebaseRemoteConfig; import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings; import kr.pe.ssun.bark.database.DatabaseManager; import kr.pe.ssun.bark.login.FacebookLoginHelper; import kr.pe.ssun.bark.login.GoogleLoginHelper; import kr.pe.ssun.bark.network.NetworkUtil; import kr.pe.ssun.bark.storage.StorageManager; /** * Created by x1210x on 2016. 8. 15.. */ public class MainModel { private static final String TAG = MainModel.class.getSimpleName(); private final static String REMOTE_CONFIG_WELCOME_MESSAGE = "bark_welcome_message"; private MainPresenter mMainPresenter; private GoogleLoginHelper mGoogleLoginHelper; private FacebookLoginHelper mFacebookLoginHelper; private FirebaseRemoteConfig mFirebaseRemoteConfig; MainModel(MainPresenter mainPresenter, FragmentActivity activity) { this.mMainPresenter = mainPresenter; initFirebase(); fetchFirebaseRemoteConfig(); uploadUserDataToFirebase(); mGoogleLoginHelper = new GoogleLoginHelper(activity); mFacebookLoginHelper = new FacebookLoginHelper(new FacebookLoginHelper.FacebookLoginHelperListener() { @Override public void handleFacebookAccessToken(AccessToken token) { // do nothing } }); } private void initFirebase() { initFirebaseRemoteConfig(); initFirebaseDatabase(); } private void initFirebaseRemoteConfig() { mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder() .setDeveloperModeEnabled(BuildConfig.DEBUG) .build(); mFirebaseRemoteConfig.setConfigSettings(configSettings); } private void initFirebaseDatabase() { // Write a message to the database FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("users"); myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. // String value = dataSnapshot.getValue(String.class); // Log.d(TAG, "[x1210x] Value is: " + value); } @Override public void onCancelled(DatabaseError error) { // Failed to read value // Log.w(TAG, "[x1210x] Failed to read value.", error.toException()); } }); } private void fetchFirebaseRemoteConfig() { long cacheExpiration = 3600; // 1 hour in seconds. // If in developer mode cacheExpiration is set to 0 so each fetch will retrieve values from // the server. if (mFirebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) { cacheExpiration = 0; } mFirebaseRemoteConfig.fetch(cacheExpiration) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { mFirebaseRemoteConfig.activateFetched(); } else { } String welcomeMessage = mFirebaseRemoteConfig.getString(REMOTE_CONFIG_WELCOME_MESSAGE); android.util.Log.d(TAG, "[x1210x] welcomeMesasge=" + welcomeMessage); mMainPresenter.setHelloText(welcomeMessage); } }); } private void uploadUserDataToFirebase() { FirebaseUser user = mMainPresenter.getCurrentUser(); DatabaseManager.getInstance().writeNewUser( user.getUid(), user.getDisplayName(), user.getEmail()); if (user.getPhotoUrl() != null) { StorageManager.getInstance().uploadPhoto( user.getUid(), user.getPhotoUrl().toString()); } } public void logOut() { // Google sign out mGoogleLoginHelper.signOut(); // Facebook log out mFacebookLoginHelper.logout(); } public void bark() { NetworkUtil.getInstance().httpGet("http://ssun.pe.kr/send.jsp"); } public void register(String token) { NetworkUtil.getInstance().httpGet("http://ssun.pe.kr/register.jsp" + "?token=" + token); } public void unregister(String token) { NetworkUtil.getInstance().httpGet("http://ssun.pe.kr/unregister.jsp" + "?token=" + token); } }
package br.com.scd.demo.api.associated; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import br.com.scd.demo.api.associated.dto.AssociatedResponse; import br.com.scd.demo.api.associated.dto.AssociatedResponseFactory; import br.com.scd.demo.associated.Associated; import br.com.scd.demo.associated.AssociatedService; import io.swagger.annotations.ApiOperation; @RestController @RequestMapping("/associateds") public class AssociatedApi { @Autowired private AssociatedService associatedService; @GetMapping @ApiOperation("Listagem dos associados disponíveis para votação.") public ResponseEntity<List<AssociatedResponse>> findAll() { List<Associated> associateds = associatedService.findAll(); List<AssociatedResponse> response = associateds.stream() .map(AssociatedResponseFactory::getInstance) .collect(Collectors.toList()); return ResponseEntity.ok(response); } }
package com.asack_software_group.tools.quchan_citizen.fragment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.asack_software_group.tools.quchan_citizen.ActivityEuclidTotal; import com.asack_software_group.tools.quchan_citizen.ActivityMap; import com.asack_software_group.tools.quchan_citizen.ActivityNineGridUniversity; import com.asack_software_group.tools.quchan_citizen.ActivityNineGridTourism; import com.asack_software_group.tools.quchan_citizen.ActivityPhoneList; import com.asack_software_group.tools.quchan_citizen.G; import com.etiennelawlor.imagegallery.library.activities.ImageGalleryActivity; import com.etiennelawlor.imagegallery.library.enums.PaletteColorType; import com.github.florent37.materialviewpager.MaterialViewPagerHelper; import com.github.ksoichiro.android.observablescrollview.ObservableScrollView; import com.asack_software_group.tools.quchan_citizen.R; import java.util.ArrayList; public class FragmentScrollCity extends Fragment { ImageView imgTourism; ImageView imgCouncil; ImageView imgManagers; ImageView imgMap; ImageView imgArt; ImageView imgUniversity; ImageView imgGallery; ImageView imgPhone; ImageView imgElders; private ObservableScrollView mScrollView; public static FragmentScrollCity newInstance() { return new FragmentScrollCity(); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_scroll_city, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mScrollView = (ObservableScrollView) view.findViewById(R.id.scrollView); MaterialViewPagerHelper.registerScrollView(getActivity(), mScrollView, null); imgTourism = (ImageView) view.findViewById(R.id.imgTourism); imgCouncil = (ImageView) view.findViewById(R.id.imgCouncil); imgManagers = (ImageView) view.findViewById(R.id.imgManagers); imgMap = (ImageView) view.findViewById(R.id.imgMap); imgArt = (ImageView) view.findViewById(R.id.imgArt); imgUniversity = (ImageView) view.findViewById(R.id.imgUniversity); imgGallery = (ImageView) view.findViewById(R.id.imgGallery); imgPhone = (ImageView) view.findViewById(R.id.imgPhone); imgElders = (ImageView) view.findViewById(R.id.imgElders); imgCouncil.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ActivityEuclidTotal.class); G.activityType = "Council"; startActivity(intent); } }); imgManagers.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ActivityEuclidTotal.class); G.activityType = "Managers"; startActivity(intent); } }); imgElders.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ActivityEuclidTotal.class); G.activityType = "Elders"; startActivity(intent); } }); imgArt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ActivityEuclidTotal.class); G.activityType = "Artists"; startActivity(intent); } }); imgTourism.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ActivityNineGridTourism.class); startActivity(intent); } }); imgUniversity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ActivityNineGridUniversity.class); startActivity(intent); } }); imgGallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(G.currentActivity, ImageGalleryActivity.class); ArrayList<String> images = G.galleryImages; intent.putStringArrayListExtra("images", images); intent.putExtra("palette_color_type", PaletteColorType.VIBRANT); startActivity(intent); getActivity().overridePendingTransition(R.anim.open_from_middle, 0); } }); imgMap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { G.pagerFilter.clear(); for(int i=0; i<G.pagerCameraPositions.size(); i++){ G.pagerFilter.add(i); } Intent intent = new Intent(getActivity(), ActivityMap.class); startActivity(intent); } }); imgPhone.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ActivityPhoneList.class); startActivity(intent); } }); } }