text
stringlengths
10
2.72M
package com.lq.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "t_isbn") public class Isbn { //序号:作为表的主键,书的isbn号 @Id @Column(length = 32) private String isbn; //书名 @Column(length = 32) private String title; //副标题 @Column(length = 32) private String subtitle; //书的图片 @Column(length = 64) private String picture; //书的作者 @Column(length = 32) private String author; //书的摘要 @Column(length = 256) private String summary; //出版社 @Column(length = 32) private String publisher; //出版地 @Column(length = 32) private String pubplace; //出版时间 @Column(length = 32) private String pubdate; //页数 @Column(length = 32) private String page; //价格 @Column(length = 32) private String price; //装帧方式 @Column(length = 32) private String binding; //ISBN 10位 @Column(length = 32) private String isbn10; //主题词 @Column(length = 32) private String keyword; //版次 @Column(length = 32) private String edition; //印次 @Column(length = 32) private String impression; //正文语种 @Column(length = 32) private String language; //开本 @Column(length = 32) private String format; //中图法分类 @Column(length = 32) private String category; public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubtitle() { return subtitle; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getPubplace() { return pubplace; } public void setPubplace(String pubplace) { this.pubplace = pubplace; } public String getPubdate() { return pubdate; } public void setPubdate(String pubdate) { this.pubdate = pubdate; } public String getPage() { return page; } public void setPage(String page) { this.page = page; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getBinding() { return binding; } public void setBinding(String binding) { this.binding = binding; } public String getIsbn10() { return isbn10; } public void setIsbn10(String isbn10) { this.isbn10 = isbn10; } public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; } public String getEdition() { return edition; } public void setEdition(String edition) { this.edition = edition; } public String getImpression() { return impression; } public void setImpression(String impression) { this.impression = impression; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
package com.cxxt.mickys.playwithme.view.adapter; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; /** * BaseDataAdapter * 基类适配器 * * @author huangyz0918 */ public class BaseDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { } @Override public int getItemCount() { return 0; } }
package com.memefilter.imagefilter.impl; import com.memefilter.imagefilter.ImageFilter; import org.bytedeco.javacpp.BytePointer; import org.bytedeco.javacpp.lept; import org.bytedeco.javacpp.lept.PIX; import org.bytedeco.javacpp.tesseract; import org.springframework.stereotype.Component; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import static org.bytedeco.javacpp.lept.pixDestroy; import static org.bytedeco.javacpp.lept.pixRead; import static org.bytedeco.javacpp.lept.pixReadMem; import static org.bytedeco.javacpp.tesseract.*; /** * Created by aross on 18/02/17. */ @Component("imageFilter") public class MemeImageFilter implements ImageFilter { @Override public String getImageText(final BufferedImage image) { if (image == null) { throw new IllegalArgumentException("Image must not be null."); } TessBaseAPI api = new TessBaseAPI(); // Initialize tesseract-ocr with English, without specifying tessdata path if (api.Init("/usr/share/tesseract/tessdata", "eng") != 0) { throw new IllegalStateException("Could not initialize tesseract."); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(image, "png", baos); } catch (IOException e) { throw new IllegalStateException("Error writing image to buffer.", e); } byte[] bytes = baos.toByteArray(); PIX pixImage = pixReadMem(bytes, bytes.length); api.SetImage(pixImage); // Get OCR result final BytePointer outText = api.GetUTF8Text(); // Destroy used object and release memory api.End(); final String result = outText.getString(); outText.deallocate(); pixDestroy(pixImage); return result; } }
/** * */ package net.sf.taverna.t2.component.ui.menu.component; import static java.awt.Color.RED; import static javax.swing.JOptionPane.CANCEL_OPTION; import static javax.swing.JOptionPane.OK_OPTION; import static javax.swing.JOptionPane.QUESTION_MESSAGE; import static javax.swing.JOptionPane.YES_NO_OPTION; import static javax.swing.JOptionPane.showOptionDialog; import static javax.swing.SwingUtilities.invokeLater; import static net.sf.taverna.t2.component.ui.serviceprovider.ComponentServiceIcon.getIcon; import static net.sf.taverna.t2.workbench.views.graph.GraphViewComponent.graphControllerMap; import static org.apache.log4j.Logger.getLogger; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JOptionPane; import net.sf.taverna.t2.component.api.Component; import net.sf.taverna.t2.component.api.ComponentFileType; import net.sf.taverna.t2.component.api.Family; import net.sf.taverna.t2.component.api.Registry; import net.sf.taverna.t2.component.api.Version; import net.sf.taverna.t2.component.registry.ComponentVersionIdentification; import net.sf.taverna.t2.component.ui.panel.ComponentChoiceMessage; import net.sf.taverna.t2.component.ui.panel.ComponentVersionChooserPanel; import net.sf.taverna.t2.lang.observer.Observable; import net.sf.taverna.t2.lang.observer.Observer; import net.sf.taverna.t2.workbench.file.FileManager; import net.sf.taverna.t2.workbench.file.exceptions.OpenException; import net.sf.taverna.t2.workbench.models.graph.GraphController; import net.sf.taverna.t2.workbench.models.graph.svg.SVGGraph; import net.sf.taverna.t2.workbench.ui.impl.Workbench; import net.sf.taverna.t2.workflowmodel.Dataflow; import org.apache.log4j.Logger; /** * @author alanrw * */ public class OpenWorkflowFromComponentAction extends AbstractAction { private static final long serialVersionUID = 7382677337746318211L; private static final Logger logger = getLogger(OpenWorkflowFromComponentAction.class); private static final String ACTION_NAME = "Open component..."; private static final String ACTION_DESCRIPTION = "Open the workflow that implements a component"; private static final FileManager fm = FileManager.getInstance(); public OpenWorkflowFromComponentAction(final java.awt.Component component) { putValue(SMALL_ICON, getIcon()); putValue(NAME, ACTION_NAME); putValue(SHORT_DESCRIPTION, ACTION_DESCRIPTION); } @Override public void actionPerformed(ActionEvent arg) { final ComponentVersionChooserPanel panel = new ComponentVersionChooserPanel(); final JButton okay = new JButton("OK"); okay.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getOptionPane((JComponent) e.getSource()).setValue(OK_OPTION); doOpen(panel.getChosenRegistry(), panel.getChosenFamily(), panel.getChosenComponent(), panel.getChosenComponentVersion()); } }); okay.setEnabled(false); // Only enable the OK button of a component is not null panel.getComponentChooserPanel().addObserver( new Observer<ComponentChoiceMessage>() { @Override public void notify( Observable<ComponentChoiceMessage> sender, ComponentChoiceMessage message) throws Exception { okay.setEnabled(message.getChosenComponent() != null); } }); final JButton cancel = new JButton("Cancel"); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getOptionPane((JComponent)e.getSource()).setValue(CANCEL_OPTION); } }); showOptionDialog(Workbench.getInstance(), panel, "Component version choice", YES_NO_OPTION, QUESTION_MESSAGE, null, new Object[] { okay, cancel }, okay); } protected JOptionPane getOptionPane(JComponent parent) { if (parent instanceof JOptionPane) return (JOptionPane) parent; return getOptionPane((JComponent) parent.getParent()); } private void doOpen(Registry registry, Family family, Component component, Version version) { Version.ID ident = new ComponentVersionIdentification( registry.getRegistryBase(), family.getName(), component.getName(), version.getVersionNumber()); try { Dataflow d = fm.openDataflow(ComponentFileType.instance, ident); final GraphController gc = graphControllerMap.get(d); invokeLater(new Runnable() { @Override public void run() { if (gc != null) { SVGGraph g = (SVGGraph) gc.getGraph(); g.setFillColor(RED); gc.redraw(); } } }); } catch (OpenException e) { logger.error("Failed to open component definition", e); } } }
package org.valdi.entities.disguise; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import org.bukkit.entity.EntityType; import org.valdi.entities.management.VersionHelper; /** * This enum contains all types, you can disguise as. * * @since 2.1.3 * @author RobinGrether */ public enum DisguiseType { BAT(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntityBat"), BLAZE(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntityBlaze"), CAVE_SPIDER(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntityCaveSpider"), CHICKEN(Type.MOB, VersionHelper.EARLIEST, AgeableDisguise.class, "EntityChicken"), COW(Type.MOB, VersionHelper.EARLIEST, AgeableDisguise.class, "EntityCow"), CREEPER(Type.MOB, VersionHelper.EARLIEST, CreeperDisguise.class, "EntityCreeper"), DONKEY(Type.MOB, VersionHelper.EARLIEST, ChestedHorseDisguise.class, "EntityHorseDonkey"), ELDER_GUARDIAN(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntityGuardianElder"), ENDER_DRAGON(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntityEnderDragon"), ENDERMAN(Type.MOB, VersionHelper.EARLIEST, EndermanDisguise.class, "EntityEnderman"), ENDERMITE(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntityEndermite"), EVOKER(Type.MOB, "v1_11_R1", MobDisguise.class, "EntityEvoker"), GHAST(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntityGhast"), GIANT(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntityGiantZombie"), GUARDIAN(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntityGuardian"), HORSE(Type.MOB, VersionHelper.EARLIEST, StyledHorseDisguise.class, "EntityHorse"), HUSK(Type.MOB, "v1_10_R1", AgeableDisguise.class, "EntityZombieHusk"), ILLUSIONER(Type.MOB, "v1_12_R1", MobDisguise.class, "EntityIllagerIllusioner"), IRON_GOLEM(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntityIronGolem"), LLAMA(Type.MOB, "v1_11_R1", LlamaDisguise.class, "EntityLlama"), MAGMA_CUBE(Type.MOB, VersionHelper.EARLIEST, SizedDisguise.class, "EntityMagmaCube"), MULE(Type.MOB, VersionHelper.EARLIEST, ChestedHorseDisguise.class, "EntityHorseMule"), MUSHROOM_COW(Type.MOB, VersionHelper.EARLIEST, AgeableDisguise.class, "EntityMushroomCow"), OCELOT(Type.MOB, VersionHelper.EARLIEST, OcelotDisguise.class, "EntityOcelot"), PARROT(Type.MOB, "v1_12_R1", ParrotDisguise.class, "EntityParrot"), PIG(Type.MOB, VersionHelper.EARLIEST, PigDisguise.class, "EntityPig"), PIG_ZOMBIE(Type.MOB, VersionHelper.EARLIEST, AgeableDisguise.class, "EntityPigZombie"), POLAR_BEAR(Type.MOB, "v1_10_R1", AgeableDisguise.class, "EntityPolarBear"), RABBIT(Type.MOB, VersionHelper.EARLIEST, RabbitDisguise.class, "EntityRabbit"), SHEEP(Type.MOB, VersionHelper.EARLIEST, SheepDisguise.class, "EntitySheep"), SHULKER(Type.MOB, "v1_9_R1", MobDisguise.class, "EntityShulker"), SILVERFISH(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntitySilverfish"), SKELETAL_HORSE(Type.MOB, VersionHelper.EARLIEST, HorseDisguise.class, "EntityHorseSkeleton"), SKELETON(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntitySkeleton"), SLIME(Type.MOB, VersionHelper.EARLIEST, SizedDisguise.class, "EntitySlime"), SNOWMAN(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntitySnowman"), SPIDER(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntitySpider"), SQUID(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntitySquid"), STRAY(Type.MOB, "v1_10_R1", MobDisguise.class, "EntitySkeletonStray"), UNDEAD_HORSE(Type.MOB, VersionHelper.EARLIEST, HorseDisguise.class, "EntityHorseZombie"), VEX(Type.MOB, "v1_11_R1", MobDisguise.class, "EntityVex"), VILLAGER(Type.MOB, VersionHelper.EARLIEST, VillagerDisguise.class, "EntityVillager"), VINDICATOR(Type.MOB, "v1_11_R1", MobDisguise.class, "EntityVindicator"), WITCH(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntityWitch"), WITHER(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntityWither"), WITHER_SKELETON(Type.MOB, VersionHelper.EARLIEST, MobDisguise.class, "EntitySkeletonWither"), WOLF(Type.MOB, VersionHelper.EARLIEST, WolfDisguise.class, "EntityWolf"), ZOMBIE(Type.MOB, VersionHelper.EARLIEST, AgeableDisguise.class, "EntityZombie"), ZOMBIE_VILLAGER(Type.MOB, VersionHelper.EARLIEST, ZombieVillagerDisguise.class, "EntityZombieVillager"), PLAYER(Type.PLAYER, VersionHelper.EARLIEST, PlayerDisguise.class, "EntityPlayer"), AREA_EFFECT_CLOUD(Type.OBJECT, "v1_9_R1", AreaEffectCloudDisguise.class, "EntityAreaEffectCloud"), ARMOR_STAND(Type.OBJECT, VersionHelper.EARLIEST, ArmorStandDisguise.class, "EntityArmorStand"), BOAT(Type.OBJECT, VersionHelper.EARLIEST, BoatDisguise.class, "EntityBoat"), ENDER_CRYSTAL(Type.OBJECT, VersionHelper.EARLIEST, ObjectDisguise.class, "EntityEnderCrystal"), FALLING_BLOCK(Type.OBJECT, VersionHelper.EARLIEST, FallingBlockDisguise.class, "EntityFallingBlock"), ITEM(Type.OBJECT, VersionHelper.EARLIEST, ItemDisguise.class, "EntityItem"), MINECART(Type.OBJECT, VersionHelper.EARLIEST, MinecartDisguise.class, "EntityMinecartRideable"); private final Type type; private final String requiredVersion; private final Class<? extends Disguise> disguiseClass; private final String nmsClass; private String translation; private DisguiseType(Type type, String requiredVersion, Class<? extends Disguise> disguiseClass, String nmsClass) { this.type = type; this.requiredVersion = requiredVersion; this.disguiseClass = disguiseClass; this.nmsClass = nmsClass; this.translation = getDefaultCommandArgument(); } /** * Checks whether the type is a mob. * * @since 2.1.3 * @return true if it's a mob, false if not */ public boolean isMob() { return type == Type.MOB; } /** * Checks whether the type is a player. * * @since 2.1.3 * @return true if it's a player, false if not */ public boolean isPlayer() { return type == Type.PLAYER; } /** * Checks whether the type is an object. * * @since 2.1.3 * @return true if it's an object, false if not */ public boolean isObject() { return type == Type.OBJECT; } /** * Returns the type of this disguise type. * * @since 2.2.2 * @return the type */ public Type getType() { return type; } /** * Indicates whether this disguise type is available on this server. * * @since 5.3.1 * @return <code>true</code>, if and only if this disguise type is available */ public boolean isAvailable() { return VersionHelper.requireVersion(requiredVersion); } /** * Returns the class that handles the subtypes for this disguise type. * * @since 5.3.1 * @return the disguise class that handles the subtypes for this disguise type */ public Class<? extends Disguise> getDisguiseClass() { return disguiseClass; } /** * Creates and returns a new instance of the correspondent disguise class.<br> * This is not supported for {@link DisguiseType#PLAYER}. * * @since 5.1.1 * @throws UnsupportedOperationException if the type is {@link DisguiseType#PLAYER} * @return the new instance or <code>null</code>, if the instantiation failed */ public Disguise newInstance() { if(!isAvailable()) { throw new OutdatedServerException(); } try { return disguiseClass.getDeclaredConstructor(new Class<?>[0]).newInstance(new Object[0]); } catch(NoSuchMethodException e) { try { return disguiseClass.getDeclaredConstructor(DisguiseType.class).newInstance(this); } catch(NoSuchMethodException e2) { throw new UnsupportedOperationException(); } catch(Exception e2) { return null; } } catch(Exception e) { return null; } } /** * @since 5.5.1 */ public String getNMSClass() { return nmsClass; } private static final Map<String, DisguiseType> commandMatcher = new ConcurrentHashMap<String, DisguiseType>(); static { for(DisguiseType type : values()) { commandMatcher.put(type.getDefaultCommandArgument(), type); } } /** * Gets the default (english) command argument.<br> * Calling this method is similar to: <code>type.name().toLowerCase(Locale.ENGLISH).replace('_', '-')</code> * * @since 5.1.1 */ public String getDefaultCommandArgument() { return name().toLowerCase(Locale.ENGLISH).replace('_', '-'); } /** * Gets the custom (probably translated) command argument.<br> * The custom command argument may be set via {@link #setCustomCommandArgument(String)}.<br> * This command argument is shown whenever <em>/disguise help</em> is run. * * @since 5.7.1 */ public String getCustomCommandArgument() { return translation; } /** * Sets the custom command argument.<br> * This command argument is shown whenever <em>/disguise help</em> is executed. * * @since 5.7.1 * @return <code>false</code> in case the given command argument is already registered */ public boolean setCustomCommandArgument(String customCommandArgument) { // TODO: adapt iDisguise.class and Language.class customCommandArgument = customCommandArgument.toLowerCase(Locale.ENGLISH).replace('_', '-'); if(commandMatcher.containsKey(customCommandArgument)) return false; translation = customCommandArgument; commandMatcher.put(customCommandArgument, this); return true; } /** * Adds another custom command argument.<br> * This command argument will <strong>NOT</strong> be shown when <em>/disguise help</em> is executed. * * @since 5.7.1 * @return <code>false</code> in case the given command argument is already registered */ public boolean addCustomCommandArgument(String customCommandArgument) { customCommandArgument = customCommandArgument.toLowerCase(Locale.ENGLISH).replace('_', '-'); if(commandMatcher.containsKey(customCommandArgument)) return false; commandMatcher.put(customCommandArgument, this); return true; } /** * Returns a string representation of the object. * * @since 5.3.1 * @return a string representation of the object */ public String toString() { return getDefaultCommandArgument(); } /** * Match a disguise type from one of its registered command arguments.<br> * Notice: This operation is case-insensitive. * * @since 5.7.1 * @return the disguise type that belongs to the given command argument or <code>null</code> if the given command argument is not registered */ public static DisguiseType fromString(String commandArgument) { commandArgument = commandArgument.toLowerCase(Locale.ENGLISH).replace('_', '-'); return commandMatcher.get(commandArgument); } /** * Match a disguise type from the equivalent entity type. * * @since 5.7.1 * @return the equivalent disguise type or <code>null</code> if there is no equivalent */ public static DisguiseType fromEntityType(EntityType entityType) { try { return DisguiseType.valueOf(entityType.name().replace("DROPPED_", "").replace("SKELETON_", "SKELETAL_").replace("ZOMBIE_H", "UNDEAD_H").replaceAll("MINECART.*", "MINECART")); } catch(IllegalArgumentException e) { return null; } } private static final Random random = new Random(); /** * Creates a random disguise type. * * @since 2.2.2 * @param type the type the disguise type should be, if this is null the type is ignored * @return a random disguise type */ public static DisguiseType random(Type type) { List<DisguiseType> types = new ArrayList<DisguiseType>(Arrays.asList(values())); if(type != null) { int pos = 0; while(pos < types.size()) { if(types.get(pos).getType() != type || !types.get(pos).isAvailable()) { types.remove(pos); } else { pos++; } } } DisguiseType randomType = types.get(random.nextInt(types.size())); return randomType; } /** * The type a disguise can be: mob, player, object. * * @since 2.1.3 * @author RobinGrether */ public enum Type { MOB, PLAYER, OBJECT; } /** * This class provides the capability to match a {@linkplain DisguiseType} from one of its command arguments. * * @since 5.1.1 * @author RobinGrether * @deprecated Replaced by {@link DisguiseType#fromString(String)}. */ @Deprecated public static class Matcher { /** * Find a matching {@linkplain DisguiseType} from one of its command arguments. * * @since 5.1.1 * @param string the command argument * @return the matching {@linkplain DisguiseType}, if one is found * @deprecated Replaced by {@link DisguiseType#fromString(String)}. */ @Deprecated public static DisguiseType match(String string) { return commandMatcher.get(string.toLowerCase(Locale.ENGLISH).replace('_', '-')); } } }
package com.vvv.kodilan.model; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.PostLoad; import javax.persistence.PrePersist; import com.vvv.kodilan.view.enums.POST_STATUS; import com.vvv.kodilan.view.enums.POST_TYPE; import lombok.AccessLevel; import lombok.Data; import lombok.Getter; import lombok.Setter; @Data @Entity public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private String id; private String slug; private String position; private String description; private String applyUrl; private String applyEmail; @OneToOne(cascade = CascadeType.ALL) private Location location; @Basic @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private Integer type; private POST_TYPE postType; @Basic @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private Integer status; private POST_STATUS postStatus; private Integer isFeatured; private Date createdAt; private Date updatedAt; private String postUrl; @OneToOne(cascade = CascadeType.ALL) private Company company; @JoinTable @OneToMany(fetch = FetchType.EAGER) private List<Tag> tags; @PostLoad void fillTransient() { if (status > 0) { this.postStatus = POST_STATUS.fromString(status.toString()); } // if (type > 0) { // this.postType = POST_TYPE.fromId(status); // } } @PrePersist void fillPersistent() { if (postStatus != null) { this.status = postStatus.getId(); } if (postType != null) { this.type = postType.getId(); } } }
package com.mobdeve.ramos.isa; public class Image { private String imagename; private byte[] image; public Image(String imagename, byte[] image) { this.imagename = imagename; this.image = image; } public String getImagename() { return imagename; } public void setImagename(String imagename) { this.imagename = imagename; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } }
package edu.computerpower.student.xmlserverdata.serverobjects1; import javax.xml.bind.annotation.*; import java.util.ArrayList; import java.util.List; @XmlAccessorType(XmlAccessType.FIELD) public class Player { @XmlAttribute(name="username") private String username; private int highScore; private List<Integer> previousscore = new ArrayList<Integer>(); public Player() { } public Player(String username, int highScore, List<Integer> previousScores) { setUsername(username); setHighScore(highScore); setPreviousScores(previousScores); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getHighScore() { return highScore; } public void setHighScore(int highScore) { this.highScore = highScore; } public List<Integer> getPreviousScores() { return previousscore; } public void setPreviousScores(List<Integer> previousScores) { this.previousscore = previousScores; } }
package br.com.rafagonc.tjdata.repositories; import br.com.rafagonc.tjdata.models.ESAJMovimentacao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * Created by rafagonc on 29/06/17. */ @Repository public interface ESAJMovimentacaoRepository extends JpaRepository<ESAJMovimentacao, Long> { }
package com.david.secretsanta.services; import com.david.secretsanta.models.PersonFamily; import com.david.secretsanta.models.SecretSantaRelationship; import java.util.Set; public interface SecretSantaGenerator { Set<SecretSantaRelationship> generate (Set <PersonFamily> personFamilies); }
/** * Copyright (C) Alibaba Cloud Computing, 2012 * All rights reserved. * * 版权所有 (C)阿里巴巴云计算,2012 */ package com.aliyun.oss.common.comm; import static com.aliyun.oss.common.utils.CodingUtils.assertParameterNotNull; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.aliyun.oss.ClientConfiguration; import com.aliyun.oss.ClientErrorCode; import com.aliyun.oss.ClientException; import com.aliyun.oss.HttpMethod; import com.aliyun.oss.ServiceException; import com.aliyun.oss.common.parser.ResultParseException; import com.aliyun.oss.common.parser.ResultParser; import com.aliyun.oss.common.utils.HttpUtil; import com.aliyun.oss.common.utils.ResourceManager; import com.aliyun.oss.common.utils.ServiceConstants; /** * The client that accesses Aliyun services. */ public abstract class ServiceClient { /** * A wrapper class to HttpMessage. * It contains the data to create HttpRequestBase, * and it is easy for testing to verify the built data such as URL, content. */ public static class Request extends HttpMesssage{ private String uri; private HttpMethod method; private boolean useUrlSignature = false; private boolean useChunkEncoding = false; public Request(){ } public String getUri(){ return this.uri; } public void setUrl(String uri){ this.uri = uri; } /** * @return the method */ public HttpMethod getMethod() { return method; } /** * @param method the method to set */ public void setMethod(HttpMethod method) { this.method = method; } public boolean isUseUrlSignature() { return useUrlSignature; } public void setUseUrlSignature(boolean useUrlSignature) { this.useUrlSignature = useUrlSignature; } public boolean isUseChunkEncoding() { return useChunkEncoding; } public void setUseChunkEncoding(boolean useChunkEncoding) { this.useChunkEncoding = useChunkEncoding; } } private static final int DEFAULT_MARK_LIMIT = 1024 * 4; private static final Log log = LogFactory.getLog(ServiceClient.class); private static ResourceManager rm = ResourceManager.getInstance(ServiceConstants.RESOURCE_NAME_COMMON); private ClientConfiguration config; protected ServiceClient(ClientConfiguration config){ this.config = config; } public ClientConfiguration getClientConfiguration(){ return this.config; } /** * Returns response result from the service. * @param request * Request message. * @param parser * Result parser. * @param context * Execution Context. * @return Result object of the specified type. * @throws Exception */ @SuppressWarnings("unchecked") public <T> T sendRequest(RequestMessage request, ExecutionContext context, ResultParser parser) throws ServiceException, ClientException{ assertParameterNotNull(parser, "parser"); ResponseMessage response = sendRequest(request, context); try{ return (T)parser.getObject(response); } catch (ResultParseException e) { throw new ClientException(response.getRequestId(), ClientErrorCode.INVALID_RESPONSE , rm.getString("FailedToParseResponse"), e); } finally{ try { response.close(); } catch (IOException e) { /* Could be silent if just closing response failed.*/ } } } /** * Returns response from the service. * @param request * Request message. * @param context * Result context. */ public ResponseMessage sendRequest(RequestMessage request, ExecutionContext context) throws ServiceException, ClientException{ assertParameterNotNull(request, "request"); assertParameterNotNull(context, "context"); try{ return sendRequestImpl(request, context); } finally { // Close the request stream as well after the request is complete. try { request.close(); } catch (IOException e) { } } } private ResponseMessage sendRequestImpl(RequestMessage request, ExecutionContext context) throws ClientException, ServiceException { RetryStrategy retryStrategy = context.getRetryStrategy() != null ? context.getRetryStrategy() : this.getDefaultRetryStrategy(); // Sign the request if a signer is provided. if (context.getSigner() != null && !request.isUseUrlSignature()) { context.getSigner().sign(request); } int retries = 0; ResponseMessage response = null; InputStream content = request.getContent(); if (content != null && content.markSupported()) { content.mark(DEFAULT_MARK_LIMIT); } while (true) { try { if (retries > 0) { pause(retries, retryStrategy); if (content != null && content.markSupported()) { content.reset(); } } Request httpRequest = buildRequest(request, context); // post process request handleRequest(httpRequest, context.getResquestHandlers()); response = sendRequestCore(httpRequest, context); handleResponse(response, context.getResponseHandlers()); return response; } catch (ServiceException ex) { // Notice that the response should not be closed in the // finally block because if the request is successful, // the response should be returned to the callers. closeResponseSilently(response); if (!shouldRetry(ex, request, response, retries, retryStrategy)) { throw ex; } } catch (ClientException ex) { // Notice that the response should not be closed in the // finally block because if the request is successful, // the response should be returned to the callers. closeResponseSilently(response); if (ex.getErrorCode().equals(ClientErrorCode.INVALID_RESPONSE)) { throw ex; } // If response invalid, no need to retry if (!shouldRetry(ex, request, response, retries, retryStrategy)) { throw ex; } } catch (Exception ex) { // Notice that the response should not be closed in the // finally block because if the request is successful, // the response should be returned to the callers. closeResponseSilently(response); throw new ClientException(rm.getFormattedString( "ConnectionError", ex.getMessage()), ex); } finally { retries ++; } } } /** * Implements the core logic to send requests to Aliyun services. * @param request * @param context * @return * @throws Exception */ protected abstract ResponseMessage sendRequestCore(Request request, ExecutionContext context) throws Exception; private Request buildRequest(RequestMessage requestMessage, ExecutionContext context) throws ClientException{ Request request = new Request(); request.setMethod(requestMessage.getMethod()); request.setUseChunkEncoding(requestMessage.isUseChunkEncoding()); if (requestMessage.isUseUrlSignature()) { request.setUrl(requestMessage.getAbsoluteUrl().toString()); request.setUseUrlSignature(true); request.setContent(requestMessage.getContent()); request.setContentLength(requestMessage.getContentLength()); request.setHeaders(requestMessage.getHeaders()); return request; } request.setHeaders(requestMessage.getHeaders()); // The header must be converted after the request is signed, // otherwise the signature will be incorrect. if (request.getHeaders() != null){ HttpUtil.convertHeaderCharsetToIso88591(request.getHeaders()); } final String delimiter = "/"; String uri = requestMessage.getEndpoint().toString(); if (!uri.endsWith(delimiter) && (requestMessage.getResourcePath() == null || !requestMessage.getResourcePath().startsWith(delimiter))){ uri += delimiter; } if (requestMessage.getResourcePath() != null){ uri += requestMessage.getResourcePath(); } String paramString; try { paramString = HttpUtil.paramToQueryString(requestMessage.getParameters(), context.getCharset()); } catch (UnsupportedEncodingException e) { // Assertion error because the caller should guarantee the charset. throw new AssertionError(rm.getFormattedString("EncodingFailed", e.getMessage())); } /* * For all non-POST requests, and any POST requests that already have a * payload, we put the encoded params directly in the URI, otherwise, * we'll put them in the POST request's payload. */ boolean requestHasNoPayload = requestMessage.getContent() != null; boolean requestIsPost = requestMessage.getMethod() == HttpMethod.POST; boolean putParamsInUri = !requestIsPost || requestHasNoPayload; if (paramString != null && putParamsInUri) { uri += "?" + paramString; } request.setUrl(uri); if (requestIsPost && requestMessage.getContent() == null && paramString != null){ // Put the param string to the request body if POSTing and // no content. try { byte[] buf = paramString.getBytes(context.getCharset()); ByteArrayInputStream content = new ByteArrayInputStream(buf); request.setContent(content); request.setContentLength(buf.length); } catch (UnsupportedEncodingException e) { throw new AssertionError(rm.getFormattedString("EncodingFailed", e.getMessage())); } } else{ request.setContent(requestMessage.getContent()); request.setContentLength(requestMessage.getContentLength()); } return request; } private void handleResponse(ResponseMessage response, List<ResponseHandler> responseHandlers) throws ServiceException, ClientException{ for(ResponseHandler h : responseHandlers){ if (!response.isSuccessful()) { log.debug(response.getDebugInfo()); } h.handle(response); } } private void handleRequest(Request message, List<RequestHandler> resquestHandlers) throws ServiceException, ClientException{ for(RequestHandler h : resquestHandlers){ h.handle(message); } } private void pause(int retries, RetryStrategy retryStrategy) throws ClientException { long delay = retryStrategy.getPauseDelay(retries); log.debug("Retriable error detected, will retry in " + delay + "ms, attempt number: " + retries); try { Thread.sleep(delay); } catch (InterruptedException e) { throw new ClientException(e.getMessage(), e); } } private boolean shouldRetry(Exception exception, RequestMessage request, ResponseMessage response, int retries, RetryStrategy retryStrategy) { if (retries >= config.getMaxErrorRetry()) { return false; } if (!request.isRepeatable()) { return false; } if (retryStrategy.shouldRetry(exception, request, response, retries)) { log.debug("Retrying on " + exception.getClass().getName() + ": " + exception.getMessage()); return true; } return false; } private void closeResponseSilently(ResponseMessage response){ if (response != null){ try { response.close(); } catch (IOException ioe) { /* silently close the response.*/ } } } protected abstract RetryStrategy getDefaultRetryStrategy(); }
package de.cuuky.varo.listener; import java.text.SimpleDateFormat; import java.util.Date; import org.bukkit.BanEntry; import org.bukkit.BanList.Type; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; import de.cuuky.varo.Main; import de.cuuky.varo.bot.discord.VaroDiscordBot; import de.cuuky.varo.bot.discord.register.BotRegister; import de.cuuky.varo.config.config.ConfigEntry; import de.cuuky.varo.config.messages.ConfigMessages; import de.cuuky.varo.player.VaroPlayer; import de.cuuky.varo.player.stats.KickResult; import net.dv8tion.jda.core.entities.User; public class PlayerLoginListener implements Listener { @EventHandler public void onPlayerLogin(PlayerLoginEvent event) { Player player = event.getPlayer(); VaroPlayer vp = VaroPlayer.getPlayer(player) == null ? new VaroPlayer(player) : VaroPlayer.getPlayer(player); VaroDiscordBot discordBot = Main.getDiscordBot(); if(ConfigEntry.DISCORDBOT_VERIFYSYSTEM.getValueAsBoolean() && discordBot != null && discordBot.getJda() != null) { BotRegister reg = BotRegister.getRegister(event.getPlayer().getUniqueId().toString()); if(reg == null) { reg = new BotRegister(event.getPlayer().getUniqueId().toString(), true); reg.setPlayerName(event.getPlayer().getName()); event.disallow(Result.KICK_OTHER, reg.getKickMessage()); return; } else if(reg.isBypass()) { event.allow(); } else if(!reg.isActive()) { event.disallow(Result.KICK_OTHER, reg.getKickMessage()); return; } else { reg.setPlayerName(event.getPlayer().getName()); try { User user = discordBot.getJda().getUserById(reg.getUserId()); if(user == null || !discordBot.getJda().getGuildById(ConfigEntry.DISCORDBOT_SERVERID.getValueAsLong()).isMember(user)) { event.disallow(Result.KICK_OTHER, ConfigMessages.DISCORD_NO_SERVER_USER.getValue()); vp.setPlayer(null); return; } } catch(Exception e2) { System.err.println("[Varo] Es wurde keine Server ID angegeben oder die ID des Spielers ist falsch!"); } } } KickResult kickResult = vp.getStats().getKickResult(player); switch(kickResult) { case SERVER_FULL: event.disallow(Result.KICK_FULL, ConfigMessages.JOIN_KICK_SERVER_FULL.getValue(vp)); break; case NO_PROJECTUSER: event.disallow(Result.KICK_OTHER, ConfigMessages.JOIN_KICK_NOT_USER_OF_PROJECT.getValue(vp)); break; case NO_SESSIONS_LEFT: event.disallow(Result.KICK_OTHER, ConfigMessages.JOIN_KICK_NO_SESSIONS_LEFT.getValue(vp)); break; case NO_PREPRODUCES_LEFT: if(vp.getStats().getPreProduced() == 1) event.disallow(Result.KICK_OTHER, ConfigMessages.JOIN_KICK_NO_PREPRODUCES_LEFT_TODAY.getValue().replace("%days%", String.valueOf(vp.getStats().getPreProduced()))); else event.disallow(Result.KICK_OTHER, ConfigMessages.JOIN_KICK_NO_PREPRODUCES_LEFT.getValue().replace("%days%", String.valueOf(vp.getStats().getPreProduced()))); break; case NO_TIME: Date current = new Date(); long milli = vp.getStats().getTimeBanUntil().getTime() - current.getTime(); long sec = (milli / 1000) % 60; long min = (milli / 1000 * 60) % 60; long hr = (milli / 1000 * 60 * 60) % 24; String seconds = ""; String minutes = ""; String hours = ""; if(String.valueOf(sec).length() == 1) seconds = "0" + sec; else seconds = "" + sec; if(String.valueOf(min).length() == 1) minutes = "0" + min; else minutes = "" + min; if(String.valueOf(hr).length() == 1) hours = "0" + hr; else hours = "" + hr; event.disallow(Result.KICK_OTHER, ConfigMessages.JOIN_KICK_NO_TIME_LEFT.getValue().replaceAll("%timeHours%", ConfigEntry.TIME_JOIN_HOURS.getValueAsInt() + "").replaceAll("%stunden%", hours).replaceAll("%minuten%", minutes).replaceAll("%sekunden%", seconds)); break; case NOT_IN_TIME: Date date = new Date(); event.disallow(Result.KICK_OTHER, ConfigMessages.SERVER_MODT_CANT_JOIN_HOURS.getValue().replaceAll("%minHour%", String.valueOf(ConfigEntry.ONLY_JOIN_BETWEEN_HOURS_HOUR1.getValueAsInt())).replaceAll("%maxHour%", String.valueOf(ConfigEntry.ONLY_JOIN_BETWEEN_HOURS_HOUR2.getValueAsInt())).replaceAll("%hours%", new SimpleDateFormat("HH").format(date)).replaceAll("%minutes%", new SimpleDateFormat("mm").format(date)).replaceAll("%seconds%", new SimpleDateFormat("ss").format(date))); break; case DEAD: event.disallow(Result.KICK_OTHER, ConfigMessages.DEATH_KICK_DEAD.getValue()); break; case BANNED: System.out.println("TEST"); for(BanEntry entry : Bukkit.getBanList(Type.NAME).getBanEntries()) { if(entry.getTarget().equals(player.getName())) { event.disallow(Result.KICK_OTHER, ConfigMessages.JOIN_KICK_BANNED.getValue(vp).replace("%reason%", entry.getReason())); break; } } for(BanEntry entry : Bukkit.getBanList(Type.IP).getBanEntries()) { System.out.println("TARGET: " + entry.getTarget() + " : " + event.getAddress().toString()); if(entry.getTarget().equals(event.getAddress().toString())) { event.disallow(Result.KICK_OTHER, ConfigMessages.JOIN_KICK_BANNED.getValue(vp).replace("%reason%", entry.getReason())); break; } } break; case SERVER_NOT_PUBLISHED: event.disallow(Result.KICK_OTHER, ConfigMessages.JOIN_KICK_NOT_STARTED.getValue(vp)); break; case STRIKE_BAN: event.disallow(Result.KICK_OTHER, ConfigMessages.JOIN_KICK_STRIKE_BAN.getValue(vp).replace("%hours%", String.valueOf(ConfigEntry.STRIKE_BAN_AFTER_STRIKE_HOURS.getValueAsInt()))); break; default: event.allow(); if(!vp.isRegistered()) vp.register(); break; } } }
public class Main { //static String s1 = "Static Variable " + initI(); //Compilation fails: Cannot make a static reference to the non-static method initI() from the type Main static String s2 = "Static Variable " + staticInitI(); String s3 = "Instance Variable " + initI(); String s4 = "Instance Variable " + staticInitI(); public static void main(String[] args) { System.out.println(Main.s2); //prints 1 //Main.s2 = mod(Main.s2); //Compilation fails: Cannot make a static reference to the non-static method mod(String) from the type Main Main.s2 = staticMod(Main.s2); System.out.println(Main.s2); //prints 2 Main m = new Main(); System.out.println(m.s3); System.out.println(m.s4); //m.s3 = mod(m.s3); //Compilation fails. Cannot make a static reference to the non-static method mod(String) from the type Main m.s4 = staticMod(m.s4); System.out.println(m.s4); m.nonStaticMethod(); } public void nonStaticMethod() { System.out.println(s2); s2 = mod(s2); System.out.println(s2); System.out.println(s2); s2 = staticMod(s2); System.out.println(s2); System.out.println(s3); s3 = mod(s3); System.out.println(s3); System.out.println(s3); s3 = mod(s3); System.out.println(s3); System.out.println(s4); s4 = staticMod(s4); System.out.println(s4); } public String initI() { return "Instance Init"; } public static String staticInitI() { return "Static Init"; } public String mod(String x) { return x + " Instance Mod"; } public static String staticMod(String x) { return x + " Static Mod"; } }
package com.eussi._07_signature.dsa; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.junit.Assert; import org.junit.Test; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; import java.security.Signature; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; /** * Created by wangxueming on 2019/4/2. */ public class _01_JavaApiDsa { @Test public void test() { try { //实例化密钥对生成器 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); //初始化密钥对生成器 keyPairGenerator.initialize(1024, new SecureRandom()); //生成密钥对 KeyPair keyPair = keyPairGenerator.generateKeyPair(); //公钥 DSAPublicKey dsaPublicKey = (DSAPublicKey) keyPair.getPublic(); //私钥 DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) keyPair.getPrivate(); System.out.println("公钥:" + Base64.encodeBase64String(dsaPublicKey.getEncoded())); System.out.println("私钥:" + Base64.encodeBase64String(dsaPrivateKey.getEncoded())); String input = "DSA数字签名"; byte[] data = input.getBytes(); //密钥还原这里不在详述,可参考rsa算法实现 //产生签名 //实例化signature Signature signature = Signature.getInstance("SHA1withDSA"); //初始化signature signature.initSign(dsaPrivateKey); //更新 signature.update(data); //签名 byte[] sign = signature.sign(); System.out.println("签名信息:" + Hex.encodeHexString(sign)); //验证签名 //实例化signature Signature signature1 = Signature.getInstance("SHA1withDSA"); //初始化signature signature1.initVerify(dsaPublicKey); //更新 signature1.update(data); //验证 boolean status = signature1.verify(sign); Assert.assertTrue(status); System.out.println("验证结果:" + status); } catch (Exception e) { e.printStackTrace(); } } }
package component.AI; public class CIdleAI extends CAI { public CIdleAI(){ this.id = "AIIdle"; } }
// https://leetcode.com/problems/binary-tree-maximum-path-sum/ // #tree #dfs /** * Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode * right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, * TreeNode right) { this.val = val; this.left = left; this.right = right; } } */ class Solution { private int helper(TreeNode root, int[] result) { if (root == null) return 0; int left = helper(root.left, result); int right = helper(root.right, result); if (left + right + root.val > result[0]) { result[0] = left + right + root.val; } if (left + root.val > result[0]) { result[0] = left + root.val; } if (right + root.val > result[0]) { result[0] = right + root.val; } if (root.val > result[0]) { result[0] = root.val; } return Math.max(left + root.val, Math.max(right + root.val, root.val)); } public int maxPathSum(TreeNode root) { int[] result = new int[1]; result[0] = Integer.MIN_VALUE; helper(root, result); return result[0]; } }
package com.atguigu.java2; public class ThisTest2 { public static void main(String[] args) { A a = new A(); A a2 = new A(); System.out.println(a); //输出的是对象的地址值 a.say(); System.out.println("--------------------------------------------"); System.out.println(a2);//输出的是对象的地址值 a2.say(); } } class A{ //谁调用的方法this就是谁 public void say(){ System.out.println("this====" + this); } }
package hard; public class FindMaxWithoutComparison { public static int flip(int bit) { return 1 ^ bit; } /* * returns 1 if positive, 0 if negative */ public static int getSign(int number) { number = number >> 31; // Keep only last bit return flip(number & 1); } /** * if a - b > 0, a > b * * @param a * @param b * @return */ public static int getMax(int a, int b) { int signOfAMinusB = getSign(a - b); int max = signOfAMinusB * a + flip(signOfAMinusB) * b; return max; } /** * * In the above solution, condition of overflow is not addressed. * * Overflow will happen when: * * 1. a is positive and b is negative * * 2. a is negative and b is positive * * * in such case, the signOfAMinusB should be sign of a, i.e in case 1, a * should be the answer, hence use a's sign i.e 1; in case 2, a is smaller * hence a's sign is 0, hence answer will become b * * In all other cases, i.e when the signs are the same, we depend on the * sign of a - b * * @param a * @param b * @return */ public static int getMaxAddressOverflow(int a, int b) { int signOfA = getSign(a); int signOfB = getSign(b); int signOfAMinusB = getSign(a - b); int areSignsOfABDifferent = signOfA ^ signOfB; // If same, answer is 0, // if different 1 // if areSignsOfABDifferent = 1, use a's sign, else use signOfAMinusB int finalSignOperator = areSignsOfABDifferent * signOfA + flip(areSignsOfABDifferent) * signOfAMinusB; int max = finalSignOperator * a + flip(finalSignOperator) * b; return max; } public static void main(String[] args) { int a = Integer.MAX_VALUE; int b = -5; System.out.println(getMax(a, b)); System.out.println(getMaxAddressOverflow(a, b)); /** * * * int a = Integer.MAX_VALUE; int b = -5; * * System.out.println(getMax(a, b)); * System.out.println(getMaxAddressOverflow(a, b)); output: * * -5 * * 2147483647 */ } }
package dw2.projetweb.servlets; 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 java.io.IOException; import java.sql.SQLException; import java.text.ParseException; import dw2.projetweb.beans.User; import dw2.projetweb.forms.FormAdmin; @WebServlet("/Admin_inscription") public class Admin_inscription extends HttpServlet { private FormAdmin formIA = new FormAdmin(); public Admin_inscription() { super(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { if(formIA.tableExists()) { if(!formIA.adminExists()) { this.getServletContext().getRequestDispatcher("/WEB-INF/Admin/admin_inscription.jsp").forward(req, resp); } else { this.getServletContext().getRequestDispatcher("/WEB-INF/Admin/admin_connexion.jsp").forward(req, resp); } } else { formIA.createTable(req); this.getServletContext().getRequestDispatcher("/WEB-INF/Admin/admin_inscription.jsp").forward(req, resp); } } catch (SQLException throwables) { throwables.printStackTrace(); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { User u = new User(); try { u = formIA.inscrireUser(req); } catch (ParseException e) { e.printStackTrace(); } req.setAttribute("formIA", formIA); req.setAttribute("User", u); if(formIA.getErreurs().isEmpty()) { this.getServletContext().getRequestDispatcher("/WEB-INF/Admin/admin_connexion.jsp").forward(req, resp); } else { this.getServletContext().getRequestDispatcher("/WEB-INF/Admin/admin_inscription.jsp").forward(req, resp); } } }
package com.app.dao; import java.util.*; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.app.service.Service_request; import com.sun.xml.internal.org.jvnet.mimepull.MIMEMessage; public class Fields_assigner extends Service_request { public Fields_assigner() { // TODO Auto-generated constructor stub } public boolean messagesent(String name,String phone,String message) { name=super.getName(); phone=super.getPhone(); message=super.getMessage(); String recipitent=super.setFrom_phone("+12345678900"); return true; } public boolean emailsent(String name,String email,String message) { email=super.getEmail(); message=super.getMessage(); String host= "127.0.0.1";; String from=super.setFrom_email("Noreply@gmail.com"); System.out.println(from); Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(properties); try { MIMEMessage data = new MIMEMessage(session); data.setFrom(new InternetAddress(from)); data.addRecipient(data.RecipientType.TO, new InternetAddress(email)); data.setText(message); Transport.send(data); System.out.println("Email Sent successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } return true; } }
package com.zxt.framework.cache.entity; import java.util.List; public class CacheEntity { private String name;//名称 private String key;//键 private String loadType;//加载方式 private Object values;//缓存返回值 private String valuesSource;//com.xxx.xxx.test() private String createTime;//创建时间 private String createUser;//创建用户 private String previousFreshTime;//上次刷新时间 private String desc;//描述 public String getName() { return name; } public String getCreateTime() { return createTime; } public String getCreateUser() { return createUser; } public String getDesc() { return desc; } public void setName(String name) { this.name = name; } public void setCreateTime(String createTime) { this.createTime = createTime; } public void setCreateUser(String createUser) { this.createUser = createUser; } public void setDesc(String desc) { this.desc = desc; } public void setValues(List values) { this.values = values; } public String getPreviousFreshTime() { return previousFreshTime; } public void setPreviousFreshTime(String previousFreshTime) { this.previousFreshTime = previousFreshTime; } public Object getValues() { return values; } public void setValues(Object values) { this.values = values; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getLoadType() { return loadType; } public void setLoadType(String loadType) { this.loadType = loadType; } public String getValuesSource() { return valuesSource; } public void setValuesSource(String valuesSource) { this.valuesSource = valuesSource; } }
package Entities; import java.util.Arrays; public class Professor { private String nome; private int matricula; private String[] disciplinas; private int tempoDeCasa; public Professor () {} public Professor (String nome, int matricula, String[] disciplinas, int tempoDeCasa) { this.nome = nome; this.matricula = matricula; this.disciplinas = disciplinas; this.tempoDeCasa = tempoDeCasa; } public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public void setMatricula(int matricula) { this.matricula = matricula; } public void setDisciplinas(String[] disciplinas) throws Exception { if (disciplinas[0] == null) { throw new Exception("Disciplinas não pode ser nulo"); } this.disciplinas = disciplinas; } public void setTempoDeCasa(int tempoDeCasa) { this.tempoDeCasa = tempoDeCasa; } public int getMatricula() { return matricula; } public int getTempoDeCasa() { return tempoDeCasa; } public String[] getDisciplinas() { return disciplinas; } @Override public String toString() { return "Professor:" + " nome = " + nome + '\'' + ", matricula = " + matricula + ", disciplinas = " + Arrays.toString(disciplinas) + ", tempoDeCasa = " + tempoDeCasa + " ano"; } }
package asset_code; public class Piercingshot { }
package Solution; import java.util.Arrays; /* Given an array, and an element to insert, and the position to insert this element. Return a new array with the element inserted. */ public class InsertArray { public static int[] insert(int[] array, int num, int position){ int[] newArray = new int[array.length + 1]; position = Math.min(array.length, position); for(int i = 0; i < position; i++){ newArray[i] = array[i]; } newArray[position] = num; for(int j = position; j < array.length; j++){ newArray[j + 1] = array[j]; } return newArray; } public static void main(String[] args){ int[] array = new int[] {1, 3, 5, 6, 9}; int num = 5; int position = 4; System.out.println(Arrays.toString(insert(array, num, position))); } } /* Is it possible to write a version of this method that returns void and changes x in place? No. Because array has fixed initialized length, so to add an element, you need to create a new array. */
package nesto.fragmenttest; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import nesto.base.util.LogUtil; /** * Created on 2016/7/7. * By nesto */ public class SimpleFragment extends Fragment { private static final String ARG_SECTION_NUMBER = "section_number"; private TextView textView; public static SimpleFragment newInstance(int sectionNumber) { SimpleFragment fragment = new SimpleFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } private int getNumber() { return getArguments().getInt(ARG_SECTION_NUMBER); } private String getName() { return "Fragment " + getNumber() + ": "; } private void restore(Bundle savedInstanceState, String methodName) { if (savedInstanceState != null) { String s = savedInstanceState.getString("hehe"); if (s != null) { printLog("restore from " + methodName); } } } @Override public void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState) { super.onInflate(context, attrs, savedInstanceState); printLog(getName() + "onInflate"); restore(savedInstanceState, "onInflate"); } private void printLog(String logInfo) { String s = getName() + logInfo; LogUtil.e(s); C.BUILDER.append(s).append("\n"); if (textView != null) { textView.setText(C.BUILDER.toString()); } } @Override public void onAttach(Context context) { printLog("onAttach"); super.onAttach(context); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { printLog("onCreate"); restore(savedInstanceState, "onCreate"); super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { printLog("onCreateView"); restore(savedInstanceState, "onCreateView"); View rootView = inflater.inflate(R.layout.fragment_main, container, false); textView = (TextView) rootView.findViewById(R.id.section_label); return rootView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); printLog("onViewCreated"); restore(savedInstanceState, "onViewCreated"); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); printLog("onActivityCreated"); restore(savedInstanceState, "onActivityCreated"); } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); printLog("onViewStateRestored"); restore(savedInstanceState, "onViewStateRestored"); } @Override public void onStart() { super.onStart(); printLog("onStart"); } @Override public void onResume() { super.onResume(); printLog("onResume"); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); printLog("onCreateOptionsMenu"); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); printLog("onPrepareOptionsMenu"); } @Override public void onPause() { super.onPause(); printLog("onPause"); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); printLog("onSaveInstanceState"); outState.putString("hehe", "hehe"); LogUtil.d("saved " + outState.getString("hehe")); } @Override public void onStop() { super.onStop(); printLog("onStop"); } @Override public void onDestroyView() { super.onDestroyView(); printLog("onDestroyView"); } @Override public void onDestroy() { super.onDestroy(); printLog("onDestroy"); } @Override public void onDetach() { super.onDetach(); printLog("onDetach"); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.aot; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.aot.generate.MethodReference.ArgumentCodeGenerator; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.AbstractBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.ResourceLoader; import org.springframework.javapoet.ClassName; import org.springframework.javapoet.CodeBlock; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ApplicationContextInitializationCodeGenerator}. * * @author Stephane Nicoll */ class ApplicationContextInitializationCodeGeneratorTests { private static final ArgumentCodeGenerator argCodeGenerator = ApplicationContextInitializationCodeGenerator. createInitializerMethodArgumentCodeGenerator(); @ParameterizedTest @MethodSource("methodArguments") void argumentsForSupportedTypesAreResolved(Class<?> target, String expectedArgument) { CodeBlock code = CodeBlock.of(expectedArgument); assertThat(argCodeGenerator.generateCode(ClassName.get(target))).isEqualTo(code); } @Test void argumentForUnsupportedBeanFactoryIsNotResolved() { assertThat(argCodeGenerator.generateCode(ClassName.get(AbstractBeanFactory.class))).isNull(); } @Test void argumentForUnsupportedEnvironmentIsNotResolved() { assertThat(argCodeGenerator.generateCode(ClassName.get(StandardEnvironment.class))).isNull(); } static Stream<Arguments> methodArguments() { String applicationContext = "applicationContext"; String environment = applicationContext + ".getEnvironment()"; return Stream.of( Arguments.of(DefaultListableBeanFactory.class, "beanFactory"), Arguments.of(ConfigurableListableBeanFactory.class, "beanFactory"), Arguments.of(ConfigurableEnvironment.class, environment), Arguments.of(Environment.class, environment), Arguments.of(ResourceLoader.class, applicationContext)); } }
package DesignPattern.Bridge; public class DealerPicker extends Picker { public DealerPicker(PersonToBridge p) { super(p); // TODO Auto-generated constructor stub } @Override public void guidTo(String somewhere) { // TODO Auto-generated method stub System.out.println("picker guiding drugdealler to the drugmarket to deal"); person.followToDo(); } }
package Arrays; public class test { static int count = 5; public static void main(String[] args) { int a[] = {12, 34, 45, 6, 13}; test obj = new test(); obj.print(a); obj.deleteFromEnd(a); obj.print(a); obj.deleteValue(a, 34); obj.print(a); obj.deleteFromPosition(a, 3); obj.print(a); } /* * It'll delete last value from array */ public void deleteFromEnd(int[] a) { if(a.length == 0) { return; } count--; } /* * It'll delete given value from array */ public void deleteValue(int a[], int val) { int i; for(i = 0; i< count; i++) { if(a[i] == val) { break; } } if(i == count) { System.out.println("Value doesn't exists in array"); return; } for(int j = i; j < count - 1; j++) { a[j] = a[j + 1]; } count--; } /* * It'll delete given value from given position in array */ public void deleteFromPosition(int a[], int position) { if(position > count || position <= 0) { System.out.println("Invalid Position"); return; } for(int i = position - 1; i < count - 1; i++) { a[i] = a[i + 1]; } count--; } public void print(int[] a) { for(int i = 0; i < count; i++) { System.out.print(a[i] + " "); } System.out.println(); } }
package def; import java.awt.Font; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import org.opencv.core.Point; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.core.MatOfRect; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier; public class faceDetection { public static void main(String[] args) { // loading the library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); /* * Instantiating classifier class */ String xmlFile = "C:\\Users\\Shirley\\eclipse-workspace\\HelloUI\\src\\xml\\face_detect.xml"; CascadeClassifier classifier = new CascadeClassifier(xmlFile); /* * Detect the faces */ // reading the image String fpath = "C:\\Users\\Shirley\\eclipse-workspace\\HelloUI\\src\\drawable\\blackpink.jpg"; Mat matrix = Imgcodecs.imread(fpath); // MatOfRect is used to draw rectangles around the face MatOfRect faceDetections = new MatOfRect(); classifier.detectMultiScale(matrix, faceDetections); System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); // drawing the boxes for (Rect rect : faceDetections.toArray()) { Point point1 = new Point(rect.x, rect.y); Point point2 = new Point(rect.x + rect.width, rect.y + rect.height); Imgproc.rectangle(matrix, point1, point2, new Scalar(0,255,0), 3); // Adding Text Imgproc.putText ( matrix, // Matrix obj of the image String.format("Detected %s faces", faceDetections.toArray().length), // Text to be added new Point(10, 50), // point Font.ITALIC , // front face 1, // front scale new Scalar(0, 255, 0), // Scalar object for color 3 // Thickness ); } System.out.println(matrix); MatOfByte matOfByte = new MatOfByte(); Imgcodecs.imencode(".jpg", matrix, matOfByte); byte[] byteArray = matOfByte.toArray(); InputStream in = new ByteArrayInputStream(byteArray); try { BufferedImage img = ImageIO.read(in); JFrame frame = new JFrame(); frame.getContentPane().add(new JLabel(new ImageIcon(img))); frame.setVisible(true); frame.pack(); frame.setTitle("OpenCV Face Detection by Jake SJK"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String writePath = new String("C:\\\\Users\\\\Shirley\\\\eclipse-workspace\\\\HelloUI\\\\src\\\\drawable\\\\saved.jpg"); Imgcodecs.imwrite(writePath, matrix); } }
package com.sinodynamic.hkgta.dao.crm; import com.sinodynamic.hkgta.dao.IBaseDao; import com.sinodynamic.hkgta.entity.crm.MemberType; public interface MemberTypeDao extends IBaseDao<MemberType>{ public MemberType getByMemberTypeName(String memberTypeName); public MemberType getByMemberTypeCode(String typeCode); }
package odevKamp4.concrete; import odevKamp4.abstracts.BaseCustomerManager; import odevKamp4.entities.Customer; public class NeroCustomerManager extends BaseCustomerManager{ @Override public void save(Customer customer) { } }
package entity; import java.util.ArrayList; import java.util.List; public class QuestionInfo { /** * 问题 * */ private Question question; /** * 用户答案 * */ private List<Integer> userAnswers=new ArrayList<Integer>(); /** * 设置正确答案 * */ public void setAnswers(List<Integer> answers){ this.question.setAnswers(answers); } /** * 获取正确答案 * */ public List<Integer> getAnswers() { return this.question.getAnswers(); } public QuestionInfo(){ } public QuestionInfo(int idx,Question question){ this.question=question; this.question.setId(idx); } public Question getQuestion() { return question; } public void setQuestion(Question question) { this.question = question; } public List<Integer> getUserAnswers() { return userAnswers; } public void setUserAnswers(List<Integer> userAnswers) { this.userAnswers = userAnswers; } public int getScore() { return this.question.getScore(); } @Override public String toString(){ return this.question.toString(); } }
package org.apache.cassandra.utils; import java.net.InetAddress; import java.util.*; import java.util.Map.Entry; import org.apache.cassandra.config.DatabaseDescriptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Tracks the network topology determined by the property file snitch to * determine the short node id we can embed in versions (timestamps) * <p> * ShortNodeIds are 16 bits, high 4 bits identify the datacenter, * low 12 bits identify the node within that datacenter. * <p> * With this setup we can handle up to 8 datacenters with up to 4096 servers in each * * @author wlloyd */ public class ShortNodeId { private static Logger logger = LoggerFactory.getLogger(ShortNodeId.class); //TODO: Keep this consistent across node failures and additions private static Map<InetAddress, Short> addrToId = new HashMap<InetAddress, Short>(); public static byte numDCs = 0; public static int maxServInDC = 0; public static InetAddress left = null, right = null; public static void updateShortNodeIds(Map<InetAddress, String[]> addrToDcAndRack) { first = true; synchronized (addrToId) { //Just doing the brain-deadest thing for now addrToId.clear(); SortedMap<String, List<InetAddress>> datacenterToAddrs = new TreeMap<String, List<InetAddress>>(); for (Entry<InetAddress, String[]> entry : addrToDcAndRack.entrySet()) { InetAddress addr = entry.getKey(); String datacenter = entry.getValue()[0]; if (!datacenterToAddrs.containsKey(datacenter)) { datacenterToAddrs.put(datacenter, new ArrayList<InetAddress>()); } datacenterToAddrs.get(datacenter).add(addr); } byte dcIndex = 0; for (List<InetAddress> addrs : datacenterToAddrs.values()) { short nodeIndex = 0; for (InetAddress addr : addrs) { assert dcIndex < 8 && nodeIndex < 4096; short fullIndex = (short) ((dcIndex << 12) + nodeIndex); addrToId.put(addr, fullIndex); nodeIndex++; } if(nodeIndex > maxServInDC) maxServInDC = nodeIndex; dcIndex++; } numDCs = dcIndex; LamportClock.setLocalId(getLocalId()); } int selfId = getNodeIdWithinDC(getLocalId()); int leftId = selfId * 2 + 1; int rightId = selfId * 2 + 2; for(Map.Entry<InetAddress, Short> entry : addrToId.entrySet()) { int localId = getNodeIdWithinDC(entry.getValue()); if(localId == leftId) left = entry.getKey(); else if(localId == rightId) right = entry.getKey(); } logger.debug("NodeIDs updated numDC = {}, maxNodes = {}", new Object[]{numDCs, maxServInDC}); VersionVector.init(numDCs, maxServInDC); } public static short getId(InetAddress addr) { synchronized (addrToId) { assert addrToId.containsKey(addr) : "addr = " + addr + " not found in " + addrToId; return addrToId.get(addr).shortValue(); } } public static byte getDC(InetAddress addr) { synchronized (addrToId) { assert addrToId.containsKey(addr) : "addr = " + addr + " not found in " + addrToId; return (byte) (addrToId.get(addr).shortValue() >> 12); } } public static short getNodeIdWithinDC(short ID) { return (short) (ID & ((1<<12)-1)); } public static short getLocalId() { return getId(DatabaseDescriptor.getListenAddress()); } static boolean first = true; public static Set<InetAddress> getNonLocalAddressesInThisDC() { Set<InetAddress> nonLocalAddresses = new HashSet<InetAddress>(); byte localDC = getLocalDC(); if(first) logger.debug("I am node {} of DC {} with address {}", new Object[]{getNodeIdWithinDC(getLocalId()), getLocalDC(), DatabaseDescriptor.getListenAddress()}); for (InetAddress addr : addrToId.keySet()) { if (getDC(addr) == localDC && !addr.equals(DatabaseDescriptor.getListenAddress())) { nonLocalAddresses.add(addr); } } if(first) for(InetAddress add: nonLocalAddresses) logger.debug("Other nodes in this DC are node = {} dc={} add={}", new Object[]{getNodeIdWithinDC(getId(add)),getDC(add), add}); first = false; return nonLocalAddresses; } public static byte getLocalDC() { return getDC(DatabaseDescriptor.getListenAddress()); } }
package server.impl; import java.util.ArrayList; import dao.IUserdao; import dao.impl.UserdaoImpl; import model.user.Car; import model.user.RentRecord; import model.user.User; import server.IUserServe; import utils.IdcardUtils; import utils.RegUtils; public class UserServeImpl implements IUserServe{ private UserdaoImpl userdao; public IUserdao getUserdao() { return userdao; } public void setUserdao(UserdaoImpl userdao) { this.userdao = userdao; } public UserServeImpl(UserdaoImpl userdao) { super(); this.userdao = userdao; } public UserServeImpl() { } @Override public String toString() { return "UserServeImpl [userdao=" + userdao + "]"; } /** *登录 */ @Override public User login(String username, String password) { User user = userdao.login(username, password); return user; } /** * 注册 */ @Override public boolean registe(User user) { //1 先判断用户名是否被注册 int i = userdao.getUserByName(user.getUsername()); int j = userdao.getUserByIdnumber(user.getIdnumber()); if(i>0){ // 被注册 System.out.println("用户名已经被注册!"); return false; }else if(j>0){ System.out.println("身份证已被注册!"); return false; }else if(!RegUtils.isMoblie(user.getTel())){ System.out.println("手机号不合法!"); return false; }else if(!IdcardUtils.validateCard(user.getIdnumber())){ System.out.println("身份证不合法!"); return false; } else{ // 可注册 userdao.registe(user); return true; } } /** * 查询所有汽车 */ @Override public ArrayList<Car> queryAllCar() { ArrayList<Car> list = userdao.queryAllCar(); return list; } /** * 升序查询 */ @Override public ArrayList<Car> queryByRentAsc() { ArrayList<Car> list = userdao.queryByRentAsc(); return list; } /** * 降序查询 */ @Override public ArrayList<Car> queryByRentDesc() { ArrayList<Car> list = userdao.queryByRentDesc(); return list; } /** * 车型查询 */ @Override public ArrayList<Car> queryByModel(String model) { ArrayList<Car> queryAllCar = userdao.queryAllCar(); ArrayList<Car> list=null; for (Car car : queryAllCar) { if(car.getModel().equals(model)){ list= userdao.queryByModel(model); }else{ System.out.println("请输入正确车型!"); return null; } } return list; } /** * 类型查询 */ @Override public ArrayList<Car> queryByCategory(String category) { ArrayList<Car> queryAllCar = userdao.queryAllCar(); ArrayList<String> list= new ArrayList<String>(); for (Car car : queryAllCar) { //if(car.getCategory().equals(category)){ list.add(car.getCategory()); //} } if(!list.contains(category)){ System.out.println("暂无该类型的车辆!"); return null; } else{ ArrayList<Car> queryByCategory = userdao.queryByCategory(category); System.out.println("汽车id\t车牌号\t品牌\t颜色\t类型\t备注信息\t\t价格\t\t租金\t租赁状态\t上架状态\t车型"); for (Car car : queryByCategory) { System.out.println(car); } return null; } } /** * 品牌查询 */ @Override public ArrayList<Car> queryByBrand(String brand) { ArrayList<Car> queryAllCar = userdao.queryAllCar(); ArrayList<String> list= new ArrayList<String>(); for (Car car : queryAllCar) { //if(car.getBrand().equals(brand)){ list.add(car.getBrand()); //} } if(!list.contains(brand.trim())){ System.out.println("请输入正确品牌!"); return null; } else{ ArrayList<Car> queryByBrand = userdao.queryByBrand(brand.trim()); System.out.println("汽车id\t车牌号\t品牌\t颜色\t类型\t备注信息\t\t价格\t\t租金\t租赁状态\t上架状态\t车型"); for (Car car : queryByBrand) { System.out.println(car); } return null; } } /** * 查询当前用户的所有租赁记录 */ @Override public ArrayList<RentRecord> queryRecord(User user) { ArrayList<RentRecord> list = userdao.queryRecord(user); return list; } /** * 租车 */ @Override public void rentCar(int userid, int carid) { ArrayList<Car> queryAllCar = userdao.queryAllCar(); int flag=0; for (Car car : queryAllCar) { if(car.getId()==carid){ flag=1; break; } } if(flag==1){ userdao.RentCar(userid, carid); System.out.println("租车成功!即时开始计费"); }else{ System.out.println("该车不存在 或 已经被租用!"); } } /** * 还车 */ @Override public void returnCar(int userid, int recordid1) { boolean flag=true; RentRecord rentRecord = userdao.queryRecordByRecordId(userid, recordid1); if(rentRecord==null){ System.out.println("请输入正确的记录编号!"); }else{ if(rentRecord.getId()==recordid1&&rentRecord.getPayment()>=0){ userdao.returnCar(userid, recordid1,rentRecord.getCarid()); System.out.println("还车成功!"); RentRecord record = userdao.queryRecordByRecordId(userid, recordid1); System.out.println("支付金额:"+record.getPayment()); }else{ System.out.println("出现错误 ,还车失败!"); } } } }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.util; import java.util.Comparator; import java.util.Map; /** * Strategy interface for {@code String}-based path matching. * * <p>Used by {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}, * {@link org.springframework.web.servlet.handler.AbstractUrlHandlerMapping}, * and {@link org.springframework.web.servlet.mvc.WebContentInterceptor}. * * <p>The default implementation is {@link AntPathMatcher}, supporting the * Ant-style pattern syntax. * * @author Juergen Hoeller * @since 1.2 * @see AntPathMatcher */ public interface PathMatcher { /** * Does the given {@code path} represent a pattern that can be matched * by an implementation of this interface? * <p>If the return value is {@code false}, then the {@link #match} * method does not have to be used because direct equality comparisons * on the static path Strings will lead to the same result. * @param path the path to check * @return {@code true} if the given {@code path} represents a pattern */ boolean isPattern(String path); /** * Match the given {@code path} against the given {@code pattern}, * according to this PathMatcher's matching strategy. * @param pattern the pattern to match against * @param path the path to test * @return {@code true} if the supplied {@code path} matched, * {@code false} if it didn't */ boolean match(String pattern, String path); /** * Match the given {@code path} against the corresponding part of the given * {@code pattern}, according to this PathMatcher's matching strategy. * <p>Determines whether the pattern at least matches as far as the given base * path goes, assuming that a full path may then match as well. * @param pattern the pattern to match against * @param path the path to test * @return {@code true} if the supplied {@code path} matched, * {@code false} if it didn't */ boolean matchStart(String pattern, String path); /** * Given a pattern and a full path, determine the pattern-mapped part. * <p>This method is supposed to find out which part of the path is matched * dynamically through an actual pattern, that is, it strips off a statically * defined leading path from the given full path, returning only the actually * pattern-matched part of the path. * <p>For example: For "myroot/*.html" as pattern and "myroot/myfile.html" * as full path, this method should return "myfile.html". The detailed * determination rules are specified to this PathMatcher's matching strategy. * <p>A simple implementation may return the given full path as-is in case * of an actual pattern, and the empty String in case of the pattern not * containing any dynamic parts (i.e. the {@code pattern} parameter being * a static path that wouldn't qualify as an actual {@link #isPattern pattern}). * A sophisticated implementation will differentiate between the static parts * and the dynamic parts of the given path pattern. * @param pattern the path pattern * @param path the full path to introspect * @return the pattern-mapped part of the given {@code path} * (never {@code null}) */ String extractPathWithinPattern(String pattern, String path); /** * Given a pattern and a full path, extract the URI template variables. URI template * variables are expressed through curly brackets ('{' and '}'). * <p>For example: For pattern "/hotels/{hotel}" and path "/hotels/1", this method will * return a map containing "hotel" &rarr; "1". * @param pattern the path pattern, possibly containing URI templates * @param path the full path to extract template variables from * @return a map, containing variable names as keys; variables values as values */ Map<String, String> extractUriTemplateVariables(String pattern, String path); /** * Given a full path, returns a {@link Comparator} suitable for sorting patterns * in order of explicitness for that path. * <p>The full algorithm used depends on the underlying implementation, * but generally, the returned {@code Comparator} will * {@linkplain java.util.List#sort(java.util.Comparator) sort} * a list so that more specific patterns come before generic patterns. * @param path the full path to use for comparison * @return a comparator capable of sorting patterns in order of explicitness */ Comparator<String> getPatternComparator(String path); /** * Combines two patterns into a new pattern that is returned. * <p>The full algorithm used for combining the two pattern depends on the underlying implementation. * @param pattern1 the first pattern * @param pattern2 the second pattern * @return the combination of the two patterns * @throws IllegalArgumentException when the two patterns cannot be combined */ String combine(String pattern1, String pattern2); }
package com.company; public class LivingRoom { private int tv; private int sofas; private Windows windows; private int cats; public LivingRoom(int tv, int sofas, Windows windows, int cats) { this.tv = tv; this.sofas = sofas; this.windows = windows; this.cats = cats; } public int getTv() { return tv; } public int getSofas() { return sofas; } public Windows getWindows() { return windows; } public int getCats() { return cats; } }
package com.karya.bean; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; public class BudgetBean { private int bgId; @NotNull @NotEmpty(message = "Please enter budget name") private String budgetName; @NotNull @NotEmpty(message = "Please select document status") private String docStatus; @NotNull @NotEmpty(message = "Please select center name") private String centerName; @NotNull @NotEmpty(message = "Please warn if annual bidget exceed") private String actifannualbgexceed; @NotNull @NotEmpty(message = "Please warn if monthly budget exceed") private String actifmonthbgexceed; @NotNull @NotEmpty(message = "Please enter year") private String fiscalYear; @NotNull @NotEmpty(message = "Please enter company") private String company; @NotNull @NotEmpty(message = "Please select budget account type") private String bgaccountType; private String bgAmount; public int getBgId() { return bgId; } public void setBgId(int bgId) { this.bgId = bgId; } public String getBudgetName() { return budgetName; } public void setBudgetName(String budgetName) { this.budgetName = budgetName; } public String getDocStatus() { return docStatus; } public void setDocStatus(String docStatus) { this.docStatus = docStatus; } public String getCenterName() { return centerName; } public void setCenterName(String centerName) { this.centerName = centerName; } public String getActifannualbgexceed() { return actifannualbgexceed; } public void setActifannualbgexceed(String actifannualbgexceed) { this.actifannualbgexceed = actifannualbgexceed; } public String getActifmonthbgexceed() { return actifmonthbgexceed; } public void setActifmonthbgexceed(String actifmonthbgexceed) { this.actifmonthbgexceed = actifmonthbgexceed; } public String getFiscalYear() { return fiscalYear; } public void setFiscalYear(String fiscalYear) { this.fiscalYear = fiscalYear; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getBgaccountType() { return bgaccountType; } public void setBgaccountType(String bgaccountType) { this.bgaccountType = bgaccountType; } public String getBgAmount() { return bgAmount; } public void setBgAmount(String bgAmount) { this.bgAmount = bgAmount; } }
package com.gaoshin.cloud.web.job.schedule; import com.gaoshin.cloud.web.bean.StringList; import com.gaoshin.cloud.web.job.bean.JobExecutionDetails; import com.gaoshin.cloud.web.job.bean.JobExecutionDetailsList; public interface JobExecutionManager { StringList listTaskType(); void taskExecutionSucceed(Long currentTaskExecutionEntityId); void taskExecutionFailed(Long id); void jobFailed(Long jobExecutionId); void jobSucceed(Long jobExecutionId); void checkDueJob(); JobExecutionDetailsList getJobExecutionList(Long jobId); JobExecutionDetails getJobExecutionDetails(Long jobExecutionId); }
package JavaProject; import java.io.IOException; public class Main extends Atm{ public static void main(String[] args) throws IOException { Atm optionmenu=new Atm(); optionmenu.getLogin(); } }
package com.trump.auction.account.dao; import com.trump.auction.account.domain.AccountRechargeOrder; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by wangyichao on 2017-12-19 下午 06:43. */ @Repository public interface AccountRechargeOrderDao { /** * 更新充值订单的状态 */ int updateUserAccountRechargeOrderStatus(AccountRechargeOrder userAccountRechargeOrder); int createAccountRechargeOrder(AccountRechargeOrder accountRechargeOrder); /** * 根据订单号获取订单信息 */ AccountRechargeOrder getAccountRechargeOrderByOutTradeNo(@Param("outTradeNo") String outTradeNo); /** * 更新充值订单为失败 */ int updateUserAccountRechargeOrderFailed(@Param("outTradeNo") String orderNo, @Param("tradeStatus") Integer tradeStatus, @Param("payRemark") String payRemark, @Param("resultJson") String resultJson); /** * 查询未完成的充值订单 */ List<AccountRechargeOrder> getUnfinishedRechargeOrder(@Param("tradeStatus") Integer tradeStatus, @Param("orderStatus") Integer orderStatus); }
package com.example.ade.slametinmasyarakatapp.Common; import com.example.ade.slametinmasyarakatapp.Remote.FCMClient; import com.example.ade.slametinmasyarakatapp.Remote.IFCMService; /** * Created by Ade on 22/01/2018. */ public class Common { public static final String driver_tbl = "Drivers"; public static final String user_driver_tbl = "Users"; public static final String user_rider_tbl = "Riders"; public static final String pickup_request_tbl = "PickupRequest"; public static final String token_tbl = "Tokens"; public static final String fcmURL = "https://fcm.googleapis.com/"; public static IFCMService getFCMService() { return FCMClient.getClient(fcmURL).create(IFCMService.class); } }
package org.shujito.cartonbox.model; import java.io.Serializable; public class Download implements Serializable { private static final long serialVersionUID = 1L; private long id; private String name; private String source; private String location; public long getId() { return this.id; } public String getName() { return this.name; } public String getSource() { return this.source; } public String getLocation() { return this.location; } public Download setId(long i) { this.id = i; return this; } public Download setName(String s) { this.name = s; return this; } public Download setSource(String s) { this.source = s; return this; } public Download setLocation(String s) { this.location = s; return this; } }
package com.longfellow.listnode; public class AddTwoNumbers { public ListNode addTwoNumbers(ListNode list1, ListNode list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } ListNode res = null; while (list1 != null || list2 != null) { } return res; } }
package com.emed.shopping.dao.model.admin.store; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.util.Date; public class ShopArea { @Id @GeneratedValue(generator = "JDBC") private Long id; private Date addTime; private String deleteStatus; private String areaName; private Integer level; private Integer sequence; private Long parentId; private String common; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getAddTime() { return addTime; } public void setAddTime(Date addTime) { this.addTime = addTime; } public String getDeleteStatus() { return deleteStatus; } public void setDeleteStatus(String deleteStatus) { this.deleteStatus = deleteStatus == null ? null : deleteStatus.trim(); } public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName == null ? null : areaName.trim(); } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } public Integer getSequence() { return sequence; } public void setSequence(Integer sequence) { this.sequence = sequence; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getCommon() { return common; } public void setCommon(String common) { this.common = common == null ? null : common.trim(); } }
package cn.test.dynamicProxy.javaProxy; /** * Created by xiaoni on 2020/3/4. */ public class Test { public static void main(String[] args) { JdkProxy jdkProxy = new JdkProxy(); IHouse iHouseA = jdkProxy.getInstance(new HouseA()); iHouseA.rent(); iHouseA.onlyForYou(); System.out.println("####################"); IHouse iHouseB = jdkProxy.getInstance(new HouseB()); iHouseB.rent(); iHouseB.onlyForYou(); System.out.println("####################"); IHouse iHouseC = jdkProxy.getInstance(new FinalHouseC()); iHouseC.rent(); iHouseC.onlyForYou(); } }
package model; import java.util.Calendar; import java.util.Date; public class Pickup { private String p_num; private String pu_area; private int pu_time; private Date pu_date; public String getP_num() { return p_num; } public void setP_num(String p_num) { this.p_num = p_num; } public String getPu_area() { return pu_area; } public void setPu_area(String pu_area) { this.pu_area = pu_area; } public int getPu_time() { return pu_time; } public void setPu_time(int pu_time) { this.pu_time = pu_time; } public Date getPu_date() { return pu_date; } public void setPu_date() { Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.HOUR , getPu_time()); this.pu_date = cal.getTime(); } @Override public String toString() { return "Pickup [p_num=" + p_num + ", pu_area=" + pu_area + ", pu_time=" + pu_time + ", pu_date=" + pu_date + "]"; } }
package com.chinasoft.education_manage.web.loginservlet; import cn.hutool.captcha.ShearCaptcha; import com.chinasoft.education_manage.domain.Yuangong; import com.chinasoft.education_manage.service.YuangongService; import com.chinasoft.education_manage.service.impl.YuangongServiceImpl; import com.chinasoft.education_manage.utils.CommonUtils; 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 javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Map; @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置编码集 request.setCharacterEncoding("utf-8"); //获取参数 String verifycode = request.getParameter("verifycode"); HttpSession session = request.getSession(); ShearCaptcha captcha = (ShearCaptcha) session.getAttribute("captcha"); session.removeAttribute("captcha"); //验证失败则重新登录 if (!captcha.verify(verifycode)) { request.setAttribute("msg", "验证码输入错误"); request.getRequestDispatcher("/login.jsp").forward(request, response); } //将获取的参数封装为map集合 Map<String, String[]> parameterMap = request.getParameterMap(); //调试敏感词过滤 String sname = parameterMap.get("sname")[0]; //集合这种的元素封装为对象的属性 Yuangong yuangong = CommonUtils.populate(new Yuangong(), parameterMap); YuangongService yuangongService = new YuangongServiceImpl(); Yuangong y = yuangongService.findYuangongByNameAndPassword(yuangong); if (y != null) { //表示登陆成功 session.setAttribute("yuangong", yuangong); response.sendRedirect(request.getContextPath() + "/index.jsp"); } else { request.setAttribute("msg", "用户名或密码输入错误"); request.getRequestDispatcher("/login.jsp").forward(request, response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
package com.formList.model; import java.util.Arrays; import com.emp.model.EmpVO; public class FormListVO { private String formListId; private String memberId; private String empId; private java.sql.Date formListCreateDate; private String formListType; private String formListTitle; private String formListContext; private byte[] formListFile; private String formListStatus; private String formListSolu; private java.sql.Date formListSoluDate; public static class Builder { private String formListId; private String memberId; private String empId; private java.sql.Date formListCreateDate; private String formListType; private String formListTitle; private String formListContext; private byte[] formListFile; private String formListStatus; private String formListSolu; private java.sql.Date formListSoluDate; public FormListVO.Builder formListId(String formListId) { this.formListId = formListId; return this; } public FormListVO.Builder memberId(String memberId) { this.memberId = memberId; return this; } public FormListVO.Builder empId(String empId) { this.empId = empId; return this; } public FormListVO.Builder formListCreateDate(java.sql.Date formListCreateDate) { this.formListCreateDate = formListCreateDate; return this; } public FormListVO.Builder formListType(String formListType) { this.formListType = formListType; return this; } public FormListVO.Builder formListTitle(String formListTitle) { this.formListTitle = formListTitle; return this; } public FormListVO.Builder formListContext(String formListContext) { this.formListContext = formListContext; return this; } public FormListVO.Builder formListFile(byte[] formListFile) { this.formListFile = formListFile; return this; } public FormListVO.Builder formListStatus(String formListStatus) { this.formListStatus = formListStatus; return this; } public FormListVO.Builder formListSolu(String formListSolu) { this.formListSolu = formListSolu; return this; } public FormListVO.Builder formListSoluDate(java.sql.Date formListSoluDate) { this.formListSoluDate = formListSoluDate; return this; } } public FormListVO() { super(); } private FormListVO(FormListVO.Builder builder) { formListId = builder.formListId; memberId = builder.memberId; empId = builder.empId; formListCreateDate = builder.formListCreateDate; formListType = builder.formListType; formListTitle = builder.formListTitle; formListContext = builder.formListContext; formListFile = builder.formListFile; formListStatus = builder.formListStatus; formListSolu = builder.formListSolu; formListSoluDate = builder.formListSoluDate; } public String getFormListId() { return formListId; } public void setFormListId(String formListId) { this.formListId = formListId; } public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getEmpId() { return empId; } public void setEmpId(String empId) { this.empId = empId; } public java.sql.Date getFormListCreateDate() { return formListCreateDate; } public void setFormListCreateDate(java.sql.Date formListCreateDate) { this.formListCreateDate = formListCreateDate; } public String getFormListType() { return formListType; } public void setFormListType(String formListType) { this.formListType = formListType; } public String getFormListTitle() { return formListTitle; } public void setFormListTitle(String formListTitle) { this.formListTitle = formListTitle; } public String getFormListContext() { return formListContext; } public void setFormListContext(String formListContext) { this.formListContext = formListContext; } public byte[] getFormListFile() { return formListFile; } public void setFormListFile(byte[] formListFile) { this.formListFile = formListFile; } public String getFormListStatus() { return formListStatus; } public void setFormListStatus(String formListStatus) { this.formListStatus = formListStatus; } public String getFormListSolu() { return formListSolu; } public void setFormListSolu(String formListSolu) { this.formListSolu = formListSolu; } public java.sql.Date getFormListSoluDate() { return formListSoluDate; } public void setFormListSoluDate(java.sql.Date formListSoluDate) { this.formListSoluDate = formListSoluDate; } @Override public String toString() { return "FormListVO [formListId=" + formListId + ", memberId=" + memberId + ", empId=" + empId + ", formListCreateDate=" + formListCreateDate + ", formListType=" + formListType + ", formListTitle=" + formListTitle + ", formListContext=" + formListContext + ", formListFile=" + Arrays.toString(formListFile) + ", formListStatus=" + formListStatus + ", formListSolu=" + formListSolu + ", formListSoluDate=" + formListSoluDate + "]"; } }
package com.gaoshin.appbooster.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; @Entity @Table @XmlRootElement public class Category extends DbEntity { @Column(nullable=false, length=64) private String name; @Column(nullable=true, length=64) private String source; @Column(nullable=true, length=1023) private String url; @Column(nullable=true, length=64) private String parentId; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
package com.testing.myapp.alwaysgym.Utils; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.view.MenuItem; import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx; import com.testing.myapp.alwaysgym.MainActivity; import com.testing.myapp.alwaysgym.R; import com.testing.myapp.alwaysgym.SettingsActivity; import com.testing.myapp.alwaysgym.ViewActivity; /** * Created by harsha on 11/24/18. */ public class BottomNavigationViewHelper { private static final String TAG = "BottomNavigationViewHel"; public static void setupBottomNavigationView(BottomNavigationViewEx viewEx) { viewEx.enableAnimation(false); viewEx.enableItemShiftingMode(false); viewEx.enableShiftingMode(false); viewEx.setTextVisibility(false); } public static void enableNavigation(final Context context,BottomNavigationViewEx viewEx ){ viewEx.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()){ case R.id.ic_house: Intent intent1 = new Intent(context, MainActivity.class); context.startActivity(intent1); break; case R.id.ic_search: Intent intent2 = new Intent(context, ViewActivity.class); context.startActivity(intent2); break; case R.id.ic_setting: Intent intent3 = new Intent(context, SettingsActivity.class); context.startActivity(intent3); break; } return false; } }); } }
package com.example.mcabezas.racomobile.Connect; import android.util.Log; import com.example.mcabezas.racomobile.Model.Mail; import com.example.mcabezas.racomobile.Model.Notice; import com.example.mcabezas.racomobile.ItemList; import com.example.mcabezas.racomobile.Model.ItemGeneric; import com.example.mcabezas.racomobile.Model.News; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.xml.sax.helpers.XMLReaderFactory; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; /** * Created by mcabezas on 11/02/16. */ public class XmlParser { private final String mTAG = "XMLParser"; private static XmlParser sInstancia = null; // creador sincronizado para protegerse de posibles problemas multi-hilo // otra prueba para evitar instanciación múltiple private synchronized static void crearInstancia() { if (sInstancia == null) { sInstancia = new XmlParser(); } } public static XmlParser getInstance() { if (sInstancia == null) crearInstancia(); return sInstancia; } public ItemList parserData(int tipus, URL url){ ItemList lli = new ItemList(); switch (tipus) { case AndroidUtils.TIPUS_NOTICIA:/** Noticies */ lli = parserNoticies(url); break; case AndroidUtils.TIPUS_AVISOS: lli = parserAvisos(url); break; default: break; } return lli; } public ItemList parserDataCorreu(int tipus, URL url, String username, String password) { ItemList lli; lli = parserCorreu(url, username, password); return lli; } protected ItemList parserAvisos(URL url) { ItemList lli = new ItemList(); AndroidUtils au = AndroidUtils.getInstance(); HttpURLConnection con = null; try { con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(10000); InputStream is = con.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(is); Element element = document.getDocumentElement(); NodeList nodeListGeneral = element.getElementsByTagName("item"); String urlImatge = au.URL_AVISOS_IMATGE; String[] nomAssig; if (nodeListGeneral.getLength() > 0) { for (int i = 0; i < nodeListGeneral.getLength(); i++) { Element entry = (Element) nodeListGeneral.item(i); Element titleE = (Element) entry.getElementsByTagName( "title").item(0); Element descriptionE = (Element) entry .getElementsByTagName("description").item(0); Element linkE = (Element) entry .getElementsByTagName("link").item(0); String title = titleE.getFirstChild().getNodeValue(); String description = ""; if(descriptionE.getFirstChild() != null){ description = descriptionE.getFirstChild().getNodeValue(); } String link = linkE.getFirstChild() .getNodeValue(); Element pubDateE = (Element) entry.getElementsByTagName( "pubDate").item(0); Date pubDate = AndroidUtils.dateXMLStringToDateParser(pubDateE.getFirstChild() .getNodeValue()); nomAssig = title.trim().split("-"); lli.afegirItemGeneric((ItemGeneric) new Notice(title, description, urlImatge, pubDate, AndroidUtils.TIPUS_AVISOS, nomAssig[0] ,link)); lli.afegirImatge(urlImatge); } con.disconnect(); } else { con.disconnect(); } } catch (Exception e) { con.disconnect(); e.printStackTrace(); return null; } con.disconnect(); return lli; } protected ItemList parserCorreu(URL url, String username, String password) { ItemList lli = new ItemList(); AndroidUtils au = AndroidUtils.getInstance(); String subjecte, from,direccio; Date pubDate; JsonNode rootNode; HttpURLConnection con = null; try { con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(1000); con.setUseCaches(false); con.setRequestMethod("GET"); con.setDoOutput(true); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes("username=" + username + "&password=" + password + "&max_emails="+au.MAX_CORREUS); wr.flush(); wr.close(); InputStreamReader is = new InputStreamReader(con.getInputStream()); BufferedReader br = new BufferedReader(is); StringBuilder xmlAsString = new StringBuilder(); String line; try { while((line = br.readLine()) != null) { xmlAsString.append(line); } } catch (IOException e) { e.printStackTrace(); } Log.d("XmlParser", "xmlAsString = " +xmlAsString); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(false); XmlPullParser parser = factory.newPullParser(); parser.setInput(new StringReader(xmlAsString.toString())); Log.d("XmlParser", "parser = " +parser); /* DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Document doc = null; db = dbf.newDocumentBuilder(); // doc = db.parse(is); Log.d("XmlParser", "doc parse = " +doc); doc.getDocumentElement().normalize(); Log.d("XmlParser", "doc normalize = " +doc); NodeList nodeList = doc.getElementsByTagName("item"); if(nodeList.getLength() > 0) { String url_imatge; for(int i = 0; i < nodeList.getLength(); i++) { Element entry = (Element) nodeList.item(i); Log.d("XmlParser", "entry = " +entry); } }*/ /* ObjectMapper maper = new ObjectMapper(); rootNode = maper.readValue(is, JsonNode.class); is.close(); String statusNode = rootNode.path("status").textValue(); if (statusNode.equalsIgnoreCase("0")) { return null; } else { String numNoLlegitsNode = rootNode.path("numNoLlegits").textValue(); String numLlegitsNode = rootNode.path("numMails").textValue(); // POSAR AL SERVIDOR!!! String _urlImatge = au.URL_CORREU_IMATGE; for (JsonNode node : rootNode.path("mails")) { subjecte = node.path("subject").toString(); // title from = node.path("from").toString(); // descripcio direccio=node.path("url").toString(); pubDate = AndroidUtils.dateJSONStringToDateCorreu(node.path("date").toString()); lli.afegirItemGeneric(new Mail(subjecte, from,direccio, _urlImatge, pubDate, AndroidUtils.TIPUS_CORREU, Integer .parseInt(numLlegitsNode), Integer .parseInt(numNoLlegitsNode))); lli.afegirImatge(_urlImatge); } }*/ } catch (JsonParseException e) { con.disconnect(); e.printStackTrace(); } catch (JsonMappingException e) { con.disconnect(); e.printStackTrace(); } catch (IOException e) { con.disconnect(); e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } con.disconnect(); return lli; } protected ItemList parserNoticies(URL url) { ItemList lli = new ItemList(); AndroidUtils au = AndroidUtils.getInstance(); HttpURLConnection con = null; try { con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(1000); InputStream is = con.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Document document = null; db = dbf.newDocumentBuilder(); document = db.parse(is); Element element = document.getDocumentElement(); NodeList nodeListGeneral = element.getElementsByTagName("item"); if (nodeListGeneral.getLength() > 0) { String _urlImatge; for (int i = 0; i < nodeListGeneral.getLength(); i++) { Element entry = (Element) nodeListGeneral.item(i); Element _titleE = (Element) entry.getElementsByTagName( "title").item(0); Element _descriptionE = (Element) entry .getElementsByTagName("description").item(0); Element _pubDateE = (Element) entry.getElementsByTagName( "pubDate").item(0); Element _urlImatgeE = (Element) entry.getElementsByTagName( "media:thumbnail").item(0); Element _linkE = (Element) entry.getElementsByTagName( "link").item(0); String _title = _titleE.getFirstChild().getNodeValue(); String _description = _descriptionE.getFirstChild() .getNodeValue(); String link = _linkE.getFirstChild().getNodeValue(); Date _pubDate = AndroidUtils.dateXMLStringToDateParser(_pubDateE.getFirstChild() .getNodeValue()); if (_urlImatgeE == null) { _urlImatge = au.URL_IMATGE_DEFAULT; } else { _urlImatge = _urlImatgeE.getAttribute("url"); } /** Cas explicit per les notícies */ lli.afegirItemGeneric((News) new News(_title, _description, _urlImatge, _pubDate, AndroidUtils.TIPUS_NOTICIA, link)); lli.afegirImatge(_urlImatge); } } else { con.disconnect(); } } catch (ParserConfigurationException e) { con.disconnect(); return null; } catch (SAXException e) { con.disconnect(); return null; } catch (IOException e) { con.disconnect(); return null; } catch (DOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } con.disconnect(); return lli; } }
package com.mzdhr.aadpractice.model; import android.arch.persistence.room.Database; import android.arch.persistence.room.Room; import android.arch.persistence.room.RoomDatabase; import android.arch.persistence.room.TypeConverters; import android.content.Context; import android.util.Log; /** * An abstract class using singleton Pattern to return our database when we want it. * * - entities: our tables in room case it's our Model Entry. so for each model we create a table. * - version: our database version. Need to incremented each time we update our database. * - exportSchema: write it and set it to false to not show an error. * * - TypeConverters: to let ROOM use our convert class. Because it is not compatible with date type. * * Understanding migrations with Room - Good article for updating database schema or version or migrations * https://medium.com/google-developers/understanding-migrations-with-room-f01e04b07929 */ @Database(entities = {NoteEntry.class}, version = 1, exportSchema = false) @TypeConverters(DateConverter.class) public abstract class AppDatabase extends RoomDatabase{ private static final String TAG = AppDatabase.class.getSimpleName(); private static final Object LOCK = new Object(); private static final String DATABASE_NAME = "notedatabase"; private static AppDatabase sInstance; public static AppDatabase getInstance(Context context) { if (sInstance == null) { synchronized (LOCK) { Log.d(TAG, "Creating new database instance"); sInstance = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, AppDatabase.DATABASE_NAME) // If you don’t want to provide migrations and you specifically want your // database to be cleared when you upgrade the version. // .fallbackToDestructiveMigration() .build(); } } Log.d(TAG, "Getting the database instance, no need to recreated it :)"); return sInstance; } // Defining DAOs that work with this database. public abstract NoteDao noteDao(); }
package dev.sgp.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class EditerCollaborateurController extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String registrationNumberParam = req.getParameter("registrationNumber"); if(registrationNumberParam == null){ resp.sendError(400, "un matricule est attendu"); }else{ resp.setContentType("text/html"); resp.getWriter().write("<h1>Edition de collaborateurs</h1>" + "<p>Matricule : "+registrationNumberParam); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String registrationNumberParam = req.getParameter("registrationNumber"); String titleParam = req.getParameter("title"); String nameParam = req.getParameter("name"); String firstNameParam = req.getParameter("firstName"); if(registrationNumberParam == null || titleParam == null || nameParam == null || firstNameParam == null ){ String paramNull = ""; if(registrationNumberParam == null ){ paramNull += " matricule "; } if(titleParam == null ){ paramNull += " titre "; } if(nameParam == null ){ paramNull += " nom "; } if(firstNameParam == null ){ paramNull += " prénom "; } resp.sendError(400, "Les paramètres suivants sont incorrects : "+paramNull); }else{ resp.setStatus(201); resp.setContentType("text/html"); // code HTML ecrit dans le corps de la reponse resp.getWriter().write("<h1>Edition de collaborateurs</h1>" + "<p>Création d'un collaborateur avec les informations suivantes :</p>" + "<ul>" + "<li>matricule => "+ registrationNumberParam + "</li>" + "<li>titre => "+ titleParam + "</li>" + "<li>nom => "+ nameParam + "</li>" + "<li>prénom => "+ firstNameParam + "</li>" + "</ul>"); } } }
package controle.tarefascontrole; import java.util.Scanner; public class Tarefac5 { public static void main(String[] args) { /* * Criar um programa que receba um numero e diga se ele e um numero primo * usando switch. */ Scanner entrada = new Scanner(System.in); System.out.println("Informe o Número: "); int n = entrada.nextInt(); int contador = 2,verdade=0; while(contador<n) { if(n%contador==0) { verdade++; } contador++; } switch(verdade) { case 0: System.out.println("Número Primo! "); break; default: System.out.println("Número Não Primo! "); } entrada.close(); } }
package com.gsccs.sme.plat.svg.service; import java.util.Date; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.gsccs.sme.api.domain.base.Attach; import com.gsccs.sme.plat.auth.dao.DictItemTMapper; import com.gsccs.sme.plat.auth.service.AreaService; import com.gsccs.sme.plat.svg.dao.ParkAttachMapper; import com.gsccs.sme.plat.svg.dao.ParkMapper; import com.gsccs.sme.plat.svg.model.AppealAttachT; import com.gsccs.sme.plat.svg.model.ParkAttach; import com.gsccs.sme.plat.svg.model.ParkExample; import com.gsccs.sme.plat.svg.model.ParkT; import com.gsccs.sme.plat.svg.model.SclassT; /** * 园区业务 * * @创建时间:2016.3.1 */ @Service(value = "parkService") public class ParkServiceImpl implements ParkService { @Autowired private ParkMapper parkMapper; @Autowired private ParkAttachMapper parkAttachMapper; @Autowired private AreaService areaService; /** * 根据id查询 */ @Override public ParkT findById(Long id) { ParkT t = parkMapper.selectByPrimaryKey(id); return t; } /** * 添加 */ @Override public void insert(ParkT parkT) { if (null == parkT) { return; } parkT.setAddtime(new Date()); parkT.setStatus("0"); parkMapper.insert(parkT); if (null != parkT.getAttachs() && parkT.getAttachs().size() > 0) { for (Attach attach : parkT.getAttachs()) { ParkAttach attachT = new ParkAttach(); attachT.setParkid(parkT.getId()); attachT.setFilename(attach.getFilename()); attachT.setFilepath(attach.getFilepath()); attachT.setFiletype(attach.getFiletype()); parkAttachMapper.insert(attachT); } } } /** * 修改 */ @Override public void update(ParkT parkT) { if (null != parkT) { parkMapper.updateByPrimaryKeySelective(parkT); } } @Override public List<ParkT> find(ParkT sitemT, String order, int currPage, int pageSize) { ParkExample example = new ParkExample(); ParkExample.Criteria criteria = example.createCriteria(); proSearchParam(sitemT, criteria); if (StringUtils.isNotEmpty(order)) { example.setOrderByClause(order); } else { example.setOrderByClause(" indexnum "); } example.setCurrPage(currPage); example.setPageSize(pageSize); return parkMapper.selectPageByExample(example); } @Override public void delete(Long id) { parkMapper.deleteByPrimaryKey(id); } @Override public int count(ParkT sitemT) { ParkExample example = new ParkExample(); ParkExample.Criteria criteria = example.createCriteria(); proSearchParam(sitemT, criteria); return parkMapper.countByExample(example); } public void proSearchParam(ParkT sitemT, ParkExample.Criteria criteria) { if (null != sitemT) { if (StringUtils.isNotEmpty(sitemT.getTitle())) { criteria.andTitleLike("%" + sitemT.getTitle() + "%"); } if (null != sitemT.getSvgid()) { criteria.andSvgidEqualTo(sitemT.getSvgid()); } if (null != sitemT.getSvgid()) { criteria.andSvgidEqualTo(sitemT.getSvgid()); } if (null != sitemT.getStatus()) { criteria.andStatusEqualTo(sitemT.getStatus()); } } } }
package com.sinodynamic.hkgta.service.fms; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; 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 org.apache.commons.lang.time.DateFormatUtils; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import com.sinodynamic.hkgta.dao.adm.GlobalParameterDao; import com.sinodynamic.hkgta.dao.crm.CustomerProfileDao; import com.sinodynamic.hkgta.dao.crm.StaffCoachRoasterDao; import com.sinodynamic.hkgta.dao.crm.StaffProfileDao; import com.sinodynamic.hkgta.dao.fms.CourseMasterDao; import com.sinodynamic.hkgta.dao.fms.CourseSessionDao; import com.sinodynamic.hkgta.dao.fms.CourseSessionFacilityDao; import com.sinodynamic.hkgta.dao.fms.FacilityAdditionAttributeDao; import com.sinodynamic.hkgta.dao.fms.FacilityMasterDao; import com.sinodynamic.hkgta.dao.fms.FacilityTimeslotAdditionDao; import com.sinodynamic.hkgta.dao.fms.FacilityTimeslotDao; import com.sinodynamic.hkgta.dao.fms.FacilityTimeslotLogDao; import com.sinodynamic.hkgta.dao.fms.MemberFacilityAttendanceDao; import com.sinodynamic.hkgta.dao.fms.MemberFacilityBookAdditionAttrDao; import com.sinodynamic.hkgta.dao.fms.MemberFacilityTypeBookingDao; import com.sinodynamic.hkgta.dao.fms.MemberReservedFacilityDao; import com.sinodynamic.hkgta.dao.fms.MemberReservedStaffDao; import com.sinodynamic.hkgta.dao.fms.StaffFacilityScheduleDao; import com.sinodynamic.hkgta.dao.fms.StaffTimeslotDao; import com.sinodynamic.hkgta.dao.pms.RoomFacilityTypeBookingDao; import com.sinodynamic.hkgta.dto.crm.MemberInfoDto; import com.sinodynamic.hkgta.dto.fms.BayTypeDto; import com.sinodynamic.hkgta.dto.fms.FacilityAvailabilityDto; import com.sinodynamic.hkgta.dto.fms.FacilityItemDto; import com.sinodynamic.hkgta.dto.fms.FacilityItemStatusDto; import com.sinodynamic.hkgta.dto.fms.FacilityMasterChangeDto; import com.sinodynamic.hkgta.dto.fms.FacilityMasterQueryDto; import com.sinodynamic.hkgta.dto.fms.FacilityTimeslotQueryDto; import com.sinodynamic.hkgta.dto.fms.IFacilityTimeslotLogDto; import com.sinodynamic.hkgta.entity.crm.CustomerProfile; import com.sinodynamic.hkgta.entity.crm.GlobalParameter; import com.sinodynamic.hkgta.entity.crm.StaffCoachRoaster; import com.sinodynamic.hkgta.entity.crm.StaffProfile; import com.sinodynamic.hkgta.entity.crm.StaffTimeslot; import com.sinodynamic.hkgta.entity.fms.CourseMaster; import com.sinodynamic.hkgta.entity.fms.CourseSession; import com.sinodynamic.hkgta.entity.fms.CourseSessionFacility; import com.sinodynamic.hkgta.entity.fms.FacilityAdditionAttribute; import com.sinodynamic.hkgta.entity.fms.FacilityMaster; import com.sinodynamic.hkgta.entity.fms.FacilityTimeslot; import com.sinodynamic.hkgta.entity.fms.FacilityTimeslotAddition; import com.sinodynamic.hkgta.entity.fms.FacilityTimeslotLog; import com.sinodynamic.hkgta.entity.fms.MemberFacilityAttendance; import com.sinodynamic.hkgta.entity.fms.MemberFacilityAttendancePK; import com.sinodynamic.hkgta.entity.fms.MemberFacilityBookAdditionAttr; import com.sinodynamic.hkgta.entity.fms.MemberFacilityBookAdditionAttrPK; import com.sinodynamic.hkgta.entity.fms.MemberFacilityTypeBooking; import com.sinodynamic.hkgta.entity.fms.MemberReservedFacility; import com.sinodynamic.hkgta.entity.fms.MemberReservedStaff; import com.sinodynamic.hkgta.entity.fms.StaffFacilitySchedule; import com.sinodynamic.hkgta.entity.pms.RoomFacilityTypeBooking; import com.sinodynamic.hkgta.service.ServiceBase; import com.sinodynamic.hkgta.util.CollectionUtil; import com.sinodynamic.hkgta.util.CollectionUtil.NoResultCallBack; import com.sinodynamic.hkgta.util.DateCalcUtil; import com.sinodynamic.hkgta.util.constant.Constant; import com.sinodynamic.hkgta.util.constant.FacilityStatus; import com.sinodynamic.hkgta.util.constant.GTAError; import com.sinodynamic.hkgta.util.constant.MemberFacilityTypeBookingStatus; import com.sinodynamic.hkgta.util.exception.GTACommonException; import com.sinodynamic.hkgta.util.response.ResponseResult; @Service public class FacilityMasterServiceImpl extends ServiceBase<FacilityMaster> implements FacilityMasterService { @Autowired private FacilityMasterDao facilityMasterDao; @Autowired private MemberFacilityTypeBookingDao memberFacilityTypeBookingDao; @Autowired private FacilityTimeslotDao facilityTimeslotDao; @Autowired private MemberReservedFacilityDao memberReservedFacilityDao; @Autowired private FacilityTimeslotAdditionDao facilityTimeslotAdditionDao; @Autowired private CustomerProfileDao customerProfileDao; @Autowired private MemberFacilityAttendanceDao memberFacilityAttendanceDao; @Autowired private StaffFacilityScheduleDao staffFacilityScheduleDao; @Autowired private GlobalParameterDao globalParameterDao; @Autowired private CourseSessionFacilityDao courseSessionFacilityDao; @Autowired private FacilityAdditionAttributeDao facilityAdditionAttributeDao; @Autowired StaffCoachRoasterDao staffCoachRoasterDao; @Autowired StaffTimeslotDao staffTimeslotDao; @Autowired private CourseSessionDao courseSessionDao; @Autowired private CourseMasterDao courseMasterDao; @Autowired private RoomFacilityTypeBookingDao roomFacilityTypeBookingDao; @Autowired private FacilityTypeQuotaService facilityTypeQuotaService; @Autowired private FacilityTimeslotLogDao facTimeslotLogDao; @Autowired private FacilityAdditionAttributeService facilityAdditionAttributeService; @Autowired private MemberFacilityBookAdditionAttrDao memberFacilityBookAdditionAttrDao; @Autowired private StaffProfileDao staffProfileDao; @Autowired private MemberReservedStaffDao memberReservedStaffDao; protected final Logger logger = Logger.getLogger(FacilityMasterServiceImpl.class); @Override @Transactional(propagation = Propagation.REQUIRED) public List<FacilityMaster> getFacilityMasterList(Integer venueFloor, String facilityType) { return facilityMasterDao.getFacilityMasterList(venueFloor, facilityType); } @Override @Transactional(propagation = Propagation.REQUIRED) public List<FacilityMaster> getFacilityVenueFloorList(String facilityType, String venueCode) { return facilityMasterDao.getFacilityVenueFloorList(facilityType, venueCode); } @Override @Transactional(propagation = Propagation.REQUIRED) public ResponseResult getFacilityStatus(FacilityItemStatusDto facilityItemStatusDto) { try { FacilityItemStatusDto facilityItemStatusDtoReturn = null; FacilityItemStatusDto currentFacilityItemStatusDto = new FacilityItemStatusDto(); currentFacilityItemStatusDto.setFacilityNo(facilityItemStatusDto.getFacilityNo()); currentFacilityItemStatusDto.setBeginDatetime(facilityItemStatusDto.getBeginDatetime()); currentFacilityItemStatusDto.setEndDatetime(facilityItemStatusDto.getEndDatetime()); int hourDifference = DateCalcUtil.GetDateDifferenceByType(facilityItemStatusDto.getBeginDatetime(), facilityItemStatusDto.getEndDatetime(), Calendar.HOUR_OF_DAY); if (hourDifference >= 1) { List<FacilityItemStatusDto> facilityItemStatusDtoListReturn = new ArrayList<FacilityItemStatusDto>(); List<FacilityItemStatusDto> facilityItemStatusDtoListSameReservation = new ArrayList<FacilityItemStatusDto>(); currentFacilityItemStatusDto.setEndDatetime(DateCalcUtil.GetEndTime(currentFacilityItemStatusDto.getBeginDatetime())); Map<String, Object> responseMap = new HashMap<String, Object>(); while (currentFacilityItemStatusDto.getBeginDatetime().before(facilityItemStatusDto.getEndDatetime())) { facilityItemStatusDtoReturn = facilityTimeslotDao.getFacilityStatus(currentFacilityItemStatusDto); if (null != facilityItemStatusDtoReturn) { facilityItemStatusDto.setCreateDate(facilityItemStatusDtoReturn.getCreateDate()); facilityItemStatusDtoListReturn.add(facilityItemStatusDtoReturn); } List<FacilityItemStatusDto> bookingFacilityItemStatusDtoList = getBookingInformation(facilityItemStatusDtoReturn, responseMap); facilityItemStatusDtoListSameReservation.addAll(bookingFacilityItemStatusDtoList); if (bookingFacilityItemStatusDtoList.isEmpty()) { List<FacilityItemStatusDto> courseFacilityItemStatusDtoList = getCourseSessionInformation(facilityItemStatusDtoReturn, responseMap); if (!courseFacilityItemStatusDtoList.isEmpty()) { responseMap.put(Constant.RESV_TYPE, Constant.RESV_TYPE_COURSE); appendNotRepeated(facilityItemStatusDtoListReturn, courseFacilityItemStatusDtoList, facilityItemStatusDto); } } currentFacilityItemStatusDto.setBeginDatetime(DateCalcUtil.GetNextHour(currentFacilityItemStatusDto.getBeginDatetime())); currentFacilityItemStatusDto.setEndDatetime(DateCalcUtil.GetEndTime(currentFacilityItemStatusDto.getBeginDatetime())); if (facilityItemStatusDtoReturn != null) { getFacilityName(facilityItemStatusDto, facilityItemStatusDtoReturn); } } if (facilityItemStatusDtoListSameReservation.size() > 0) { appendNotRepeated(facilityItemStatusDtoListReturn, facilityItemStatusDtoListSameReservation, facilityItemStatusDto); copyFacilityName(facilityItemStatusDtoListReturn); } if (facilityItemStatusDtoListReturn.size() > 0) { responseMap.put("memberName", getMemberName(facilityItemStatusDtoListReturn.get(0).getSalutation(), facilityItemStatusDtoListReturn.get(0).getGiven_name(), facilityItemStatusDtoListReturn.get(0).getSurname())); responseMap.put("beginDatetimeBook", facilityItemStatusDtoListReturn.get(0).getBegin_datetime_book() != null ? facilityItemStatusDtoListReturn.get(0).getBegin_datetime_book() : ""); responseMap.put("endDatetimeBook", facilityItemStatusDtoListReturn.get(0).getEnd_datetime_book() != null ? facilityItemStatusDtoListReturn.get(0).getEnd_datetime_book() : ""); responseMap.put("resvId", facilityItemStatusDtoListReturn.get(0).getResvId() != null ? facilityItemStatusDtoListReturn.get(0).getResvId() : "0"); facilityItemStatusDtoListReturn.get(0).setSalutation(null); facilityItemStatusDtoListReturn.get(0).setGiven_name(null); facilityItemStatusDtoListReturn.get(0).setSurname(null); facilityItemStatusDtoListReturn.get(0).setBegin_datetime_book(null); facilityItemStatusDtoListReturn.get(0).setEnd_datetime_book(null); } else { responseMap.put("resvId", "0"); facilityItemStatusDtoReturn = new FacilityItemStatusDto(); facilityItemStatusDtoReturn.setFacilityNo(facilityItemStatusDto.getFacilityNo()); facilityItemStatusDtoReturn.setBeginDatetime(facilityItemStatusDto.getBeginDatetime()); facilityItemStatusDtoReturn.setEndDatetime(facilityItemStatusDto.getEndDatetime()); facilityItemStatusDtoReturn.setStatus("VC"); facilityItemStatusDtoReturn.setResvId(null); getFacilityName(facilityItemStatusDto, facilityItemStatusDtoReturn); facilityItemStatusDtoReturn.setBallFeedingStatus("OFF"); facilityItemStatusDtoListReturn.add(facilityItemStatusDtoReturn); } clearNotSerialableProperty(facilityItemStatusDtoListReturn); sortByBeginDatetime(facilityItemStatusDtoListReturn); responseMap.put("timeslot", facilityItemStatusDtoListReturn); responseResult.initResult(GTAError.FacilityError.SUCCESS, responseMap); return responseResult; } else { responseResult.initResult(GTAError.FacilityError.END_SHOULD_BE_ONE_HOUR_LATER_THEN_BEGIN); return responseResult; } } catch (Exception e) { responseResult.initResult(GTAError.FacilityError.UNEXPECTED_EXCEPTION); return responseResult; } } private void clearNotSerialableProperty(List<FacilityItemStatusDto> facilityItemStatusDtoListReturn) { for (FacilityItemStatusDto facilityItemStatusDto : facilityItemStatusDtoListReturn) { facilityItemStatusDto.setFacilityTimeslot(null); facilityItemStatusDto.setResvId(null); } } private String getMemberName(String salutation, String givenName, String surName) { if (salutation != null || givenName != null || surName != null) { return salutation + " " + givenName + " " + surName; } else { return ""; } } private void getFacilityName(FacilityItemStatusDto facilityItemStatusDto, FacilityItemStatusDto facilityItemStatusDtoReturn) { if (facilityItemStatusDtoReturn != null) { FacilityMaster facilityMaster = facilityMasterDao.get(FacilityMaster.class, facilityItemStatusDto.getFacilityNo()); facilityItemStatusDtoReturn.setFacilityName(facilityMaster != null ? facilityMaster.getFacilityName() : ""); } } private void copyFacilityName(List<FacilityItemStatusDto> facilityItemStatusDtoListReturn) { if (facilityItemStatusDtoListReturn != null && facilityItemStatusDtoListReturn.size() > 0) { int index = 0; String facilityName = ""; for (FacilityItemStatusDto facilityItemStatusDto : facilityItemStatusDtoListReturn) { if (index == 0) { facilityName = facilityItemStatusDto.getFacilityName(); } else { facilityItemStatusDto.setFacilityName(facilityName); } index++; } } } private void sortByBeginDatetime(List<FacilityItemStatusDto> facilityItemStatusDtoListReturn) { if (facilityItemStatusDtoListReturn != null && facilityItemStatusDtoListReturn.size() > 0) { for (int i = 0; i < facilityItemStatusDtoListReturn.size() - 1; i++) { FacilityItemStatusDto facilityItemStatusDtoTemp = null; if (facilityItemStatusDtoListReturn.get(i).getBeginDatetime().after(facilityItemStatusDtoListReturn.get(i + 1).getBeginDatetime())) { facilityItemStatusDtoTemp = facilityItemStatusDtoListReturn.get(i); facilityItemStatusDtoListReturn.set(i, facilityItemStatusDtoListReturn.get(i + 1)); facilityItemStatusDtoListReturn.set(i + 1, facilityItemStatusDtoTemp); } } } } private List<FacilityItemStatusDto> getBookingInformation(FacilityItemStatusDto facilityItemStatusDtoReturn, Map<String, Object> responseMap) { List<FacilityItemStatusDto> facilityItemStatusDtoListReturn = new ArrayList<>(); if (facilityItemStatusDtoReturn != null && facilityItemStatusDtoReturn.getFacilityTimeslot() != null) { MemberReservedFacility memberReservedFacility = memberReservedFacilityDao .getMemberReservedFacilityListByFacilityTimeslotId( facilityItemStatusDtoReturn.getFacilityTimeslotId()); if (memberReservedFacility != null) { MemberFacilityTypeBooking memberFacilityTypeBooking = memberFacilityTypeBookingDao .getMemberFacilityTypeBooking(memberReservedFacility.getResvId()); List<FacilityItemStatusDto> facilityItemStatusDtoListSameReservationList = getFacilityTimeslotSameReservation( memberReservedFacility, facilityItemStatusDtoReturn); facilityItemStatusDtoListReturn.addAll(facilityItemStatusDtoListSameReservationList); if (memberFacilityTypeBooking != null) { if (memberFacilityTypeBooking.getExpCoachUserId() != null) { StaffProfile staffProfile = staffProfileDao.getStaffProfileByUserId(memberFacilityTypeBooking.getExpCoachUserId()); responseMap.put(Constant.COACH_NAME, staffProfile.getGivenName() + ' ' + staffProfile.getSurname()); responseMap.put(Constant.RESV_TYPE, Constant.RESV_TYPE_PRIVATE_COACHING); } else { List<RoomFacilityTypeBooking> roomBookingList = roomFacilityTypeBookingDao.getBookingByFacilityTypeBookingId(memberReservedFacility.getResvId()); if (roomBookingList != null && !roomBookingList.isEmpty()) { responseMap.put(Constant.RESV_TYPE, Constant.RESV_TYPE_GUEST_ROOM_BUNDLED); }else if(Constant.RESERVE_TYPE_MT.equals(facilityItemStatusDtoReturn.getReserveType())){ responseMap.put(Constant.RESV_TYPE, Constant.RESV_TYPE_MAINTENANCE_OFFER); } else { responseMap.put(Constant.RESV_TYPE, Constant.RESV_TYPE_MEMBER_BOOKING); } } MemberInfoDto memberInfoDto = customerProfileDao .getCustomerInfo(memberFacilityTypeBooking.getCustomerId()); if (memberInfoDto != null) { facilityItemStatusDtoReturn .setBegin_datetime_book(memberFacilityTypeBooking.getBeginDatetimeBook()); facilityItemStatusDtoReturn .setEnd_datetime_book(memberFacilityTypeBooking.getEndDatetimeBook()); facilityItemStatusDtoReturn.setSalutation(memberInfoDto.getSalutation()); facilityItemStatusDtoReturn.setGiven_name(memberInfoDto.getGivenName()); facilityItemStatusDtoReturn.setSurname(memberInfoDto.getSurname()); facilityItemStatusDtoReturn.setSalutation(memberInfoDto.getSalutation()); facilityItemStatusDtoReturn.setResvId(memberFacilityTypeBooking.getResvId()); } } } } return facilityItemStatusDtoListReturn; } private List<FacilityItemStatusDto> getCourseSessionInformation(FacilityItemStatusDto facilityItemStatusDtoReturn, Map<String, Object> responseMap) { List<FacilityItemStatusDto> facilityItemStatusDtoListSameReservation = new ArrayList<>(); if (facilityItemStatusDtoReturn != null && facilityItemStatusDtoReturn.getFacilityTimeslot() != null) { CourseSessionFacility courseSessionFacility = courseSessionFacilityDao.getCourseSessionFacility(facilityItemStatusDtoReturn.getFacilityTimeslotId()); if (null != courseSessionFacility) { List<CourseSessionFacility> courseSessionSames = courseSessionFacilityDao.getCourseSessionFacilityList(courseSessionFacility.getCourseSessionId()); CourseSession courseSession = courseSessionDao.getCourseSessionById(courseSessionFacility.getCourseSessionId()); if (courseSession != null) { CourseMaster courseMaster = courseMasterDao.get(CourseMaster.class, courseSession.getCourseId()); if (courseMaster != null) { responseMap.put(Constant.COURSE_NAME, courseMaster.getCourseName()); } } for (CourseSessionFacility sessionFacility : courseSessionSames) { FacilityTimeslot facilityTimeslotSameReservation = facilityTimeslotDao.getFacilityTimeslotById(sessionFacility.getFacilityTimeslot().getFacilityTimeslotId()); if(!FacilityStatus.CAN.name().equals(facilityTimeslotSameReservation.getStatus())){ FacilityItemStatusDto facilityItemStatusDtoSameReservation = new FacilityItemStatusDto(); facilityItemStatusDtoSameReservation.setFacilityTimeslotId(facilityTimeslotSameReservation.getFacilityTimeslotId()); facilityItemStatusDtoSameReservation.setFacilityNo(null == facilityTimeslotSameReservation.getFacilityMaster() ? 0 : facilityTimeslotSameReservation.getFacilityMaster().getFacilityNo()); facilityItemStatusDtoSameReservation.setBeginDatetime(facilityTimeslotSameReservation.getBeginDatetime()); facilityItemStatusDtoSameReservation.setEndDatetime(facilityTimeslotSameReservation.getEndDatetime()); facilityItemStatusDtoSameReservation.setStatus(facilityTimeslotSameReservation.getStatus()); facilityItemStatusDtoSameReservation.setRemark(facilityTimeslotSameReservation.getInternalRemark()); facilityItemStatusDtoSameReservation.setCreateDate(facilityTimeslotSameReservation.getCreateDate()); facilityItemStatusDtoListSameReservation.add(facilityItemStatusDtoSameReservation); facilityItemStatusDtoListSameReservation.add(facilityItemStatusDtoSameReservation); } } } } return facilityItemStatusDtoListSameReservation; } private void getBallFeedingStatus(FacilityItemStatusDto facilityItemStatusDtoReturn) { if (facilityItemStatusDtoReturn != null) { FacilityTimeslotAddition facilityTimeslotAddition = facilityTimeslotAdditionDao.getFacilityTimeslotAddition(facilityItemStatusDtoReturn.getFacilityTimeslotId()); facilityItemStatusDtoReturn.setBallFeedingStatus(facilityTimeslotAddition != null ? facilityTimeslotAddition.getBallFeedingStatus() : "OFF"); } } private void appendNotRepeated(List<FacilityItemStatusDto> facilityItemStatusDtoListReturn, List<FacilityItemStatusDto> facilityItemStatusDtoListSameReservation, FacilityItemStatusDto facilityItemStatusDto) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); for (FacilityItemStatusDto facilityItemStatusDtoB : facilityItemStatusDtoListSameReservation) { if (!FacilityStatus.CAN.name().equals(facilityItemStatusDtoB.getStatus()) && facilityItemStatusDto.getFacilityNo().equals(facilityItemStatusDtoB.getFacilityNo()) && format.format(facilityItemStatusDto.getBeginDatetime()).equals(format.format(facilityItemStatusDtoB.getBeginDatetime())) && (null == facilityItemStatusDtoB.getCreateDate() || null==facilityItemStatusDto.getCreateDate() || getDistanceTime(facilityItemStatusDtoB.getCreateDate(),facilityItemStatusDto.getCreateDate()) <= 10) ) { Boolean found = false; for (FacilityItemStatusDto facilityItemStatusDtoA : facilityItemStatusDtoListReturn) { if (facilityItemStatusDtoA.getFacilityTimeslotId().equals(facilityItemStatusDtoB.getFacilityTimeslotId())) { found = true; } } if (found == false) { getBallFeedingStatus(facilityItemStatusDtoB); facilityItemStatusDtoListReturn.add(facilityItemStatusDtoB); } } } } public static long getDistanceTime(Date startDate, Date endDate) { long diff ; long time1 = startDate.getTime(); long time2 = endDate.getTime(); if(time1<time2) diff = time2 - time1; else diff = time1 - time2; return diff/1000; } private List<FacilityItemStatusDto> getFacilityTimeslotSameReservation( MemberReservedFacility memberReservedFacility, FacilityItemStatusDto facilityItemStatusDtoReturn) { List<FacilityItemStatusDto> facilityItemStatusDtoListSameReservation = new ArrayList<>(); List<MemberReservedFacility> memberReservedFacilityListSameReservation = memberReservedFacilityDao.getMemberReservedFacilityList(memberReservedFacility.getResvId()); for (MemberReservedFacility memberReservedFacilitySameReservation : memberReservedFacilityListSameReservation) { FacilityTimeslot facilityTimeslotSameReservation = facilityTimeslotDao.getFacilityTimeslotById(memberReservedFacilitySameReservation.getFacilityTimeslotId()); FacilityItemStatusDto facilityItemStatusDtoSameReservation = new FacilityItemStatusDto(); Long facilityNo = facilityTimeslotSameReservation.getFacilityMaster().getFacilityNo(); if (!FacilityStatus.CAN.name().equals(facilityTimeslotSameReservation.getStatus()) && facilityItemStatusDtoReturn.getFacilityNo() == facilityNo) { facilityItemStatusDtoSameReservation.setFacilityTimeslotId(facilityTimeslotSameReservation.getFacilityTimeslotId()); facilityItemStatusDtoSameReservation.setFacilityNo(null == facilityTimeslotSameReservation.getFacilityMaster() ? 0 : facilityTimeslotSameReservation.getFacilityMaster().getFacilityNo()); facilityItemStatusDtoSameReservation.setBeginDatetime(facilityTimeslotSameReservation.getBeginDatetime()); facilityItemStatusDtoSameReservation.setEndDatetime(facilityTimeslotSameReservation.getEndDatetime()); facilityItemStatusDtoSameReservation.setStatus(facilityTimeslotSameReservation.getStatus()); facilityItemStatusDtoSameReservation.setRemark(facilityTimeslotSameReservation.getInternalRemark()); facilityItemStatusDtoSameReservation.setCreateDate(facilityTimeslotSameReservation.getCreateDate()); facilityItemStatusDtoListSameReservation.add(facilityItemStatusDtoSameReservation); } } return facilityItemStatusDtoListSameReservation; } @Override @Transactional(propagation = Propagation.REQUIRED, rollbackFor = GTACommonException.class) public void changeFacilityTimeslot(FacilityMasterChangeDto facilityMasterChangeDto) throws Exception { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { validateFacilityCondition(facilityMasterChangeDto, sf); FacilityMaster facilityMaster = facilityMasterDao.get(FacilityMaster.class, facilityMasterChangeDto.getTargetFacilityNo()); if(null != facilityMaster){ List<FacilityTimeslot> srcFacilityTimeslots = getSrcFacilityTimeslots(facilityMasterChangeDto, sf); if(null != srcFacilityTimeslots && srcFacilityTimeslots.size() >0){ boolean flag = updateReservation(facilityMasterChangeDto, sf,facilityMaster,srcFacilityTimeslots); if(!flag)updateCourse(facilityMasterChangeDto, sf,facilityMaster,srcFacilityTimeslots); } }else throw new GTACommonException(GTAError.FacilityError.FACILITY_NOTFOUND); } catch (GTACommonException e) { throw e; } catch (Exception e) { throw new GTACommonException(e); } } private boolean updateReservation(FacilityMasterChangeDto facilityMasterChangeDto, SimpleDateFormat sf,FacilityMaster tragetFacilityMaster,List<FacilityTimeslot> srcFacilityTimeslots) throws GTACommonException, ParseException, Exception { String srcStartdateStr = facilityMasterChangeDto.getSrcBookingDate() + " " + facilityMasterChangeDto.getSrcStartTime() + ":00:00"; String srcEnddateStr = facilityMasterChangeDto.getSrcBookingDate() + " " + facilityMasterChangeDto.getSrcEndTime() + ":59:59"; if(Constant.FACILITY_TYPE_GOLF.equals(facilityMasterChangeDto.getFacilityType())) { validateZoneAttribute(facilityMasterChangeDto.getSrcFacilityNo(), facilityMasterChangeDto.getTargetFacilityNo()); } boolean isCreateReservation = validateFacilityBooking(facilityMasterChangeDto, sf.parse(srcStartdateStr), sf.parse(srcEnddateStr), tragetFacilityMaster); long resvId = 0L; List<MemberReservedFacility> srcMemberReservedFacilitys = new ArrayList<MemberReservedFacility>(); List<Long> srcTimeslotIds = new ArrayList<Long>(); FacilityAdditionAttribute attribute = facilityAdditionAttributeDao.getFacilityAdditionAttribute(tragetFacilityMaster.getFacilityNo(), Constant.GOLFBAYTYPE); String attributeType = ""; if (attribute != null) { attributeType = attribute.getId().getAttributeId(); } String reserveType = ""; if (srcFacilityTimeslots.size() > 0) { for(FacilityTimeslot srcFacilityTimeslot : srcFacilityTimeslots){ reserveType = srcFacilityTimeslot.getReserveType(); MemberReservedFacility memberReserved = memberReservedFacilityDao.get(MemberReservedFacility.class, srcFacilityTimeslot.getFacilityTimeslotId()); if (null != memberReserved) { //Private Coaching not allow to change time if (Constant.RESERVE_TYPE_PC.equals(reserveType) && isCreateReservation) { throw new GTACommonException(GTAError.FacilityError.CANNOT_CHANGETIME); } resvId = memberReserved.getResvId(); srcMemberReservedFacilitys.add(memberReserved); } else { if (Constant.RESERVE_TYPE_CS.equals(reserveType) && Constant.GOLFBAYTYPE_CAR.equals(attributeType)) { throw new GTACommonException(GTAError.FacilityError.COACHING_STUDIO_CHANGE); } if (Constant.RESERVE_TYPE_CS.equals(reserveType) && isCreateReservation) { throw new GTACommonException(GTAError.FacilityError.CANNOT_CHANGETIME); } return false; } srcTimeslotIds.add(srcFacilityTimeslot.getFacilityTimeslotId()); } } MemberFacilityTypeBooking booking = memberFacilityTypeBookingDao.getMemberFacilityTypeBooking(resvId); if (null == booking) throw new GTACommonException(GTAError.FacilityError.BOOKING_ISNULL); if (booking.getExpCoachUserId() == null && Constant.GOLFBAYTYPE_CAR.equals(attributeType)) { throw new GTACommonException(GTAError.FacilityError.COACHING_STUDIO_CHANGE); } boolean hasAttendanceTime = getMemberFacilityHasAttendanceTime(booking); updateSrcFacilityInfo(facilityMasterChangeDto, srcFacilityTimeslots, srcMemberReservedFacilitys, booking); MemberFacilityTypeBooking newBooking = null; if(isCreateReservation){ newBooking = copyMemberFacilityTypeBooking(booking, sf, facilityMasterChangeDto); } List<MemberReservedFacility> targetReservedFacilitys = saveTargetFacilityInfo(facilityMasterChangeDto, tragetFacilityMaster, srcTimeslotIds, (isCreateReservation)?newBooking:booking, hasAttendanceTime, FacilityStatus.TA.toString().equals(facilityMasterChangeDto.getStatus())?reserveType:Constant.RESERVE_TYPE_MT); if (isCreateReservation) { if (null != booking && Constant.FACILITY_TYPE_GOLF.equalsIgnoreCase(booking.getResvFacilityType())){ saveMemberFacilityBookAdditionAttr(booking.getResvFacilityType(), booking.getResvId(),newBooking.getResvId()); } newBooking.setMemberReservedFacilitys(targetReservedFacilitys); memberFacilityTypeBookingDao.saveOrUpdate(newBooking); if (Constant.RESERVE_TYPE_MT.equals(reserveType) && booking.getFacilityTypeQty() == 1L){ booking.setStatus(MemberFacilityTypeBookingStatus.CAN.name()); } booking.setFacilityTypeQty(booking.getFacilityTypeQty()-1); memberFacilityTypeBookingDao.update(booking); } else { booking.getMemberReservedFacilitys().addAll(targetReservedFacilitys); memberFacilityTypeBookingDao.update(booking); } return true; } private List<MemberReservedFacility> saveTargetFacilityInfo(FacilityMasterChangeDto facilityMasterChangeDto, FacilityMaster tragetFacilityMaster, List<Long> srcTimeslotIds, MemberFacilityTypeBooking booking, boolean hasAttendanceTime,String reserveType) throws Exception { Timestamp currentTimestamp= new Timestamp(Calendar.getInstance().getTimeInMillis()); List<MemberReservedFacility> targetMemberReservedFacilitys = new ArrayList<MemberReservedFacility>(); FacilityTimeslot timeslot = null; int j = 0; Long srcTimeslotId = 0l; for (int i = facilityMasterChangeDto.getTargetStartTime(); i <= facilityMasterChangeDto.getTargetEndTime(); i++) { String startdateStr = facilityMasterChangeDto.getTargetBookingDate() + " " + i + ":00:00"; String enddateStr = facilityMasterChangeDto.getTargetBookingDate() + " " + i + ":59:59"; timeslot = facilityTimeslotDao.getFacilityTimeslot(tragetFacilityMaster.getFacilityNo(), DateCalcUtil.parseDateTime(startdateStr), DateCalcUtil.parseDateTime(enddateStr)); if (null == timeslot) { if (srcTimeslotIds.size() > j) srcTimeslotId = srcTimeslotIds.get(j); timeslot = createTimeslot(facilityMasterChangeDto.getUpdateBy(), DateCalcUtil.parseDateTime(startdateStr), DateCalcUtil.parseDateTime(enddateStr), tragetFacilityMaster, FacilityStatus.TA.toString().equals(facilityMasterChangeDto.getStatus())?FacilityStatus.TA.toString():FacilityStatus.OP.toString(), srcTimeslotId, currentTimestamp, reserveType); createMemberReservedInfo(facilityMasterChangeDto, booking, targetMemberReservedFacilitys, timeslot); if (j == 0 && !facilityMasterChangeDto.getStatus().equals(FacilityStatus.TA.toString())) { saveFacTimeslotLog(facilityMasterChangeDto, facilityMasterChangeDto.getFacilityType(), timeslot.getFacilityTimeslotId(), srcTimeslotId, reserveType); } j++; } else throw new GTACommonException(GTAError.FacilityError.FACILITYSTATUS_NOTVACANT); } if(!facilityMasterChangeDto.getStatus().equals(FacilityStatus.TA.toString())){ saveMemberFacilityAttendance(booking, timeslot,hasAttendanceTime); } return targetMemberReservedFacilitys; } private void updateSrcFacilityInfo(FacilityMasterChangeDto facilityMasterChangeDto, List<FacilityTimeslot> srcFacilityTimeslots, List<MemberReservedFacility> srcMemberReservedFacilitys, MemberFacilityTypeBooking booking) { if (null != srcFacilityTimeslots && srcFacilityTimeslots.size() > 0){ if(FacilityStatus.TA.name().equals(srcFacilityTimeslots.get(0).getStatus()) && srcMemberReservedFacilitys.size() > 0){ booking.getMemberReservedFacilitys().removeAll(srcMemberReservedFacilitys); } updateSrcFacilityTimeslots(facilityMasterChangeDto, srcFacilityTimeslots, booking); } } private void validateZoneAttribute(Long srcFacilityNo, Long targetFacilityNo) { FacilityAdditionAttribute srcZoneAttribute = facilityAdditionAttributeDao.getFacilityAdditionAttribute(srcFacilityNo, Constant.ZONE_ATTRIBUTE); FacilityAdditionAttribute targetZoneAttribute = facilityAdditionAttributeDao.getFacilityAdditionAttribute(targetFacilityNo, Constant.ZONE_ATTRIBUTE); if (srcZoneAttribute != null && targetZoneAttribute != null && !srcZoneAttribute.getId().getAttributeId().equals(targetZoneAttribute.getId().getAttributeId())) { throw new GTACommonException(GTAError.FacilityError.ZONE_DIFFERENCE); } } private boolean getMemberFacilityHasAttendanceTime(MemberFacilityTypeBooking booking) { MemberFacilityAttendance oldAttendance = memberFacilityAttendanceDao.getAttendaneByResvId(booking.getResvId()); if (null != oldAttendance && null != oldAttendance.getAttendTime()) return true; return false; } private void saveMemberFacilityBookAdditionAttr(String facilityType,Long oldResvId, Long newResvId) { MemberFacilityBookAdditionAttr oldAttr = memberFacilityBookAdditionAttrDao.getMemberFacilityBookAdditionAttr(oldResvId,facilityType); if (null != oldAttr) { MemberFacilityBookAdditionAttrPK pk = new MemberFacilityBookAdditionAttrPK(); pk.setResvId(newResvId); pk.setAttributeId(oldAttr.getId().getAttributeId()); MemberFacilityBookAdditionAttr memberFacilityBookAdditionAttr = new MemberFacilityBookAdditionAttr(); memberFacilityBookAdditionAttr.setId(pk); memberFacilityBookAdditionAttr.setAttrValue(oldAttr.getId().getAttributeId()); memberFacilityBookAdditionAttr.setFacilityType(facilityType); memberFacilityBookAdditionAttrDao.saveOrUpdate(memberFacilityBookAdditionAttr); } } @SuppressWarnings("unchecked") private void saveMemberFacilityAttendance(MemberFacilityTypeBooking booking, FacilityTimeslot timeslot,boolean hasAttendanceTime ) { MemberFacilityAttendance memberFacilityAttendance = new MemberFacilityAttendance(); MemberFacilityAttendancePK attendancePK = new MemberFacilityAttendancePK(); attendancePK.setCustomerId(booking.getCustomerId()); attendancePK.setFacilityTimeslotId(timeslot.getFacilityTimeslotId()); memberFacilityAttendance.setId(attendancePK); if(hasAttendanceTime)memberFacilityAttendance.setAttendTime(new Timestamp(new Date().getTime())); memberFacilityAttendanceDao.save(memberFacilityAttendance); } private void updateSrcFacilityTimeslots(FacilityMasterChangeDto changeDto, List<FacilityTimeslot> srcFacilityTimeslots, MemberFacilityTypeBooking booking) throws GTACommonException { for (FacilityTimeslot timeslotOld : srcFacilityTimeslots) { if (FacilityStatus.TA.name().equals(timeslotOld.getStatus())) { deleteFacilityTimeslot(timeslotOld); } else if (FacilityStatus.OP.name().equals(timeslotOld.getStatus()) || FacilityStatus.RS.name().equals(timeslotOld.getStatus())) { timeslotOld.setStatus(FacilityStatus.CAN.name()); timeslotOld.setUpdateBy(changeDto.getUpdateBy()); timeslotOld.setUpdateDate(new Date()); removeStaffFacilitySchedule(timeslotOld); facilityTimeslotDao.saveOrUpdate(timeslotOld); updateMemberFacilityAttendance(booking.getCustomerId(), timeslotOld.getFacilityTimeslotId()); // add new MT facility timeslot FacilityTimeslot timeslotNew = new FacilityTimeslot(); timeslotNew.setBeginDatetime(timeslotOld.getBeginDatetime()); timeslotNew.setEndDatetime(timeslotOld.getEndDatetime()); timeslotNew.setFacilityMaster(timeslotOld.getFacilityMaster()); timeslotNew.setStatus(FacilityStatus.MT.name()); timeslotNew.setUpdateBy(changeDto.getUpdateBy()); timeslotNew.setUpdateDate(new Date()); timeslotNew.setInternalRemark(changeDto.getRemark()); facilityTimeslotDao.save(timeslotNew); } else throw new GTACommonException(GTAError.FacilityError.FACILITYSTATUS_NOTOCCUPIED); } } @SuppressWarnings("unchecked") private void deleteFacilityTimeslot(FacilityTimeslot timeslotOld) { MemberReservedFacility memberReservedFacility = memberReservedFacilityDao.get(MemberReservedFacility.class, timeslotOld.getFacilityTimeslotId()); if (null != memberReservedFacility) memberReservedFacilityDao.delete(memberReservedFacility); List<MemberFacilityAttendance> memberFacilityAttendances = memberFacilityAttendanceDao.getMemberFacilityAttendanceList(timeslotOld.getFacilityTimeslotId(), 0); if (null != memberFacilityAttendances && memberFacilityAttendances.size() > 0) { for (MemberFacilityAttendance attend : memberFacilityAttendances) { memberFacilityAttendanceDao.delete(attend); } } removeStaffFacilitySchedule(timeslotOld); timeslotOld.getFacilityMaster().getFacilityTimeslots().remove(timeslotOld); timeslotOld.setFacilityTimeslotAddition(null); facilityTimeslotDao.delete(timeslotOld); } private List<FacilityTimeslot> getSrcFacilityTimeslots(FacilityMasterChangeDto facilityMasterChangeDto, SimpleDateFormat sf) throws Exception { List<FacilityTimeslot> srcFacilityTimeslots = new ArrayList<FacilityTimeslot>(); for (int i = facilityMasterChangeDto.getSrcStartTime(); i <= facilityMasterChangeDto.getSrcEndTime(); i++) { String srcStartdateStr = facilityMasterChangeDto.getSrcBookingDate() + " " + i + ":00:00"; String srcEnddateStr = facilityMasterChangeDto.getSrcBookingDate() + " " + i + ":59:59"; FacilityTimeslot srcFacilityTimeslot = facilityTimeslotDao.getFacilityTimeslot(facilityMasterChangeDto.getSrcFacilityNo(), sf.parse(srcStartdateStr), sf.parse(srcEnddateStr)); if (null != srcFacilityTimeslot) { srcFacilityTimeslots.add(srcFacilityTimeslot); } } return srcFacilityTimeslots; } private void removeStaffFacilitySchedule(FacilityTimeslot timeslotOld) { StaffFacilitySchedule staffFacilitySchedule = staffFacilityScheduleDao.getStaffFacilityScheduleByFacilityTimeslotId(timeslotOld.getFacilityTimeslotId()); if(null !=staffFacilitySchedule){ timeslotOld.setStaffFacilitySchedule(null); staffFacilityScheduleDao.delete(staffFacilitySchedule); } } @SuppressWarnings("unchecked") private void updateMemberFacilityAttendance(long customerId, long facilityTimeslotId) { MemberFacilityAttendancePK attendancePK = new MemberFacilityAttendancePK(); attendancePK.setCustomerId(customerId); attendancePK.setFacilityTimeslotId(facilityTimeslotId); MemberFacilityAttendance memberFacilityAttendance = (MemberFacilityAttendance) memberFacilityAttendanceDao.get(MemberFacilityAttendance.class, attendancePK); if (null != memberFacilityAttendance) memberFacilityAttendanceDao.deleteById(MemberFacilityAttendance.class, attendancePK); } private void createMemberReservedInfo(FacilityMasterChangeDto facilityMasterChangeDto, MemberFacilityTypeBooking booking, List<MemberReservedFacility> targetMemberReservedFacilitys, FacilityTimeslot timeslot) { MemberReservedFacility memberReservedFacility = new MemberReservedFacility(); memberReservedFacility.setFacilityTimeslotId(timeslot.getFacilityTimeslotId()); memberReservedFacility.setResvId(booking.getResvId()); targetMemberReservedFacilitys.add(memberReservedFacility); } private FacilityTimeslot createTimeslot(String updateBy, Date startdate, Date enddate, FacilityMaster facilityMaster, String facilityStatus, long oldTimeslotId, Timestamp currentTimestamp,String reserveType) throws ParseException { FacilityTimeslot timeslot = new FacilityTimeslot(); timeslot.setBeginDatetime(startdate); timeslot.setFacilityMaster(facilityMaster); if(!FacilityStatus.TA.toString().equals(facilityStatus)) timeslot.setTransferFromTimeslotId(oldTimeslotId); timeslot.setEndDatetime(enddate); timeslot.setStatus(facilityStatus); timeslot.setCreateBy(updateBy); timeslot.setCreateDate(currentTimestamp); timeslot.setReserveType(reserveType); facilityTimeslotDao.saveOrUpdate(timeslot); return timeslot; } private boolean validateFacilityBooking(FacilityMasterChangeDto facilityMasterChangeDto, Date beginDate, Date endDate, FacilityMaster facilityMaster) throws Exception { if (null != beginDate && null != endDate) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); cal.setTime(beginDate); int beginTime = cal.get(Calendar.HOUR_OF_DAY); String date = format.format(cal.getTime()); cal = Calendar.getInstance(); cal.setTime(endDate); int endTime = cal.get(Calendar.HOUR_OF_DAY); if (format.parse(facilityMasterChangeDto.getTargetBookingDate()).before(format.parse(format.format(new Date())))) throw new GTACommonException(GTAError.FacilityError.DATE_LESSTHAN_TODAY); if (format.parse(facilityMasterChangeDto.getTargetBookingDate()).compareTo(format.parse(format.format(new Date()))) == 0){ if(facilityMasterChangeDto.getStatus().equals(FacilityStatus.TA.toString())){ if(facilityMasterChangeDto.getTargetEndTime() < getDateHour(new Date())) throw new GTACommonException(GTAError.FacilityError.DATETIME_LESSTHAN_TODAY, new Object[] { getDateHour(new Date()) + ":00" }); }else { if(facilityMasterChangeDto.getTargetStartTime() < getDateHour(new Date())) throw new GTACommonException(GTAError.FacilityError.DATETIME_LESSTHAN_TODAY, new Object[] { getDateHour(new Date()) + ":00" }); } } if (date.equals(facilityMasterChangeDto.getTargetBookingDate()) && facilityMasterChangeDto.getTargetFacilityNo() == facilityMasterChangeDto.getSrcFacilityNo()) { if ((beginTime <= facilityMasterChangeDto.getTargetStartTime() && facilityMasterChangeDto.getTargetStartTime() <= endTime) || (beginTime <= facilityMasterChangeDto.getTargetEndTime() && facilityMasterChangeDto.getTargetEndTime() <= endTime)) throw new GTACommonException(GTAError.FacilityError.FACILITY_TIMESLOTCONFLICT); } if (null != facilityMaster && null != facilityMaster.getFacilityTypeBean()) { int parameterValue = getGlobalParameterValue(facilityMaster.getFacilityTypeBean().getTypeCode()); if (parameterValue > 0) { Date futureDate = getFutureDate(new Date(), parameterValue); if (format.parse(facilityMasterChangeDto.getTargetBookingDate()).after(futureDate)) throw new GTACommonException(GTAError.FacilityError.DATE_OVER_ADVANCEDPERIOD, new Object[] { parameterValue }); } } if (facilityMasterChangeDto.getStatus().equals(FacilityStatus.TA.toString())) { if (!(facilityMasterChangeDto.getSrcStartTime() == facilityMasterChangeDto.getTargetStartTime() && facilityMasterChangeDto.getSrcEndTime() == facilityMasterChangeDto.getTargetEndTime())) throw new GTACommonException(GTAError.FacilityError.FACILITY_SELECTEDTIME_NOTSAME); } if (facilityMasterChangeDto.getTargetStartTime() == beginTime && facilityMasterChangeDto.getTargetEndTime() == endTime && date.equals(facilityMasterChangeDto.getTargetBookingDate())) { return false; } } return true; } @Transactional public int getGlobalParameterValue(String facilityType) { if (!StringUtils.isEmpty(facilityType)) { String facTypeConst = Constant.FACILITY_TYPE_GOLF.equalsIgnoreCase(facilityType) ? Constant.ADVANCEDRESPERIOD_GOLF : Constant.ADVANCEDRESPERIOD_TENNIS; GlobalParameter globalParameter = globalParameterDao.get(GlobalParameter.class, facTypeConst); if (null != globalParameter) { if (!StringUtils.isEmpty(globalParameter.getParamValue())) return Integer.parseInt(globalParameter.getParamValue()); } } return 0; } public MemberFacilityTypeBooking copyMemberFacilityTypeBooking(MemberFacilityTypeBooking booking, SimpleDateFormat sf, FacilityMasterChangeDto facilityMasterChangeDto) throws ParseException { MemberFacilityTypeBooking newBooking = new MemberFacilityTypeBooking(); newBooking.setCustomerId(booking.getCustomerId()); newBooking.setResvFacilityType(booking.getResvFacilityType()); newBooking.setFacilityTypeQty(1L); newBooking.setExpCoachUserId(booking.getExpCoachUserId()); newBooking.setReserveVia(booking.getReserveVia()); newBooking.setCreateDate(new Timestamp(new Date().getTime())); newBooking.setCreateBy(facilityMasterChangeDto.getUpdateBy()); String startdateStr = facilityMasterChangeDto.getTargetBookingDate() + " " + facilityMasterChangeDto.getTargetStartTime() + ":00:00"; String enddateStr = facilityMasterChangeDto.getTargetBookingDate() + " " + facilityMasterChangeDto.getTargetEndTime() + ":59:59"; newBooking.setBeginDatetimeBook(new Timestamp(sf.parse(startdateStr).getTime())); newBooking.setEndDatetimeBook(new Timestamp(sf.parse(enddateStr).getTime())); newBooking.setStatus(MemberFacilityTypeBookingStatus.ATN.name()); memberFacilityTypeBookingDao.save(newBooking); return newBooking; } public static Date getFutureDate(Date date, int day) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH, day); return format.parse(format.format(calendar.getTime())); } public static int getDateHour(Date date) throws ParseException { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.HOUR_OF_DAY); } public static Date getDateByFormat(Date date, SimpleDateFormat format) throws ParseException { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return format.parse(format.format(calendar.getTime())); } @Override @Transactional(propagation = Propagation.REQUIRED) public ResponseResult saveFacilityStatus(FacilityItemStatusDto facilityItemStatusDto) throws Exception { Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); if (format.parse(format.format(facilityItemStatusDto.getBeginDatetime())).before(format.parse(format.format(now)))) throw new GTACommonException(GTAError.FacilityError.DATE_LESSTHAN_TODAY); if (format.parse(format.format(facilityItemStatusDto.getBeginDatetime())).compareTo(format.parse(format.format(now))) == 0 && getDateHour(facilityItemStatusDto.getBeginDatetime()) < getDateHour(now)) throw new GTACommonException(GTAError.FacilityError.DATETIME_LESSTHAN_TODAY); FacilityMaster facilityMaster = facilityMasterDao.get(FacilityMaster.class, facilityItemStatusDto.getFacilityNo()); FacilityTimeslot timeslot = facilityTimeslotDao.getFacilityTimeslot(facilityItemStatusDto.getFacilityNo(), facilityItemStatusDto.getBeginDatetime(), null); if (null != facilityMaster) { if (null == timeslot) { if (!facilityItemStatusDto.getStatus().equals(FacilityStatus.VC.toString())) { timeslot = addFacilityTimeslot(facilityItemStatusDto, facilityMaster); } } else { if (facilityItemStatusDto.getStatus().equals(FacilityStatus.VC.toString())) { //deleteFacilityTimeslot(timeslot); timeslot.setStatus(FacilityStatus.CAN.name()); } else { timeslot.setStatus(facilityItemStatusDto.getStatus()); } timeslot.setUpdateBy(facilityItemStatusDto.getUpdateBy()); timeslot.setUpdateDate(now); timeslot.setInternalRemark(facilityItemStatusDto.getRemark()); facilityTimeslotDao.saveOrUpdate(timeslot); } if (timeslot != null && timeslot.getFacilityTimeslotId() != null && FacilityStatus.MT.getDesc().equals(facilityItemStatusDto.getStatus())) { saveFacTimeslotLog(facilityItemStatusDto, facilityMaster.getFacilityTypeBean().getTypeCode(), timeslot.getFacilityTimeslotId(), null, null); } } else { throw new GTACommonException(GTAError.FacilityError.FACILITY_NOTFOUND); } responseResult.initResult(GTAError.FacilityError.SUCCESS); return responseResult; } private void saveFacTimeslotLog(IFacilityTimeslotLogDto dto, String facType, Long timeslotId, Long fromTimeslotId, String resvType) { if (dto == null) { return; } FacilityTimeslotLog log = new FacilityTimeslotLog(); log.setBeginDatetime(dto.getBeginDatetime()); log.setEndDatetime(dto.getEndDatetime() == null ? new Date(dto.getBeginDatetime().getTime() + 3600l * 1000l) : dto.getEndDatetime()); log.setFacilityNo(dto.getFacilityNo()); log.setFacilityTimeslotId(timeslotId); log.setFacilityType(facType); log.setInternalRemark(dto.getRemark()); log.setReserveType(resvType); log.setStatus(FacilityStatus.MT.getDesc()); log.setTransferFromTimeslotId(fromTimeslotId); Date now = new Date(); log.setCreateDate(now); log.setCreateBy(dto.getUpdateBy()); log.setUpdateDate(now); log.setUpdateBy(dto.getUpdateBy()); facTimeslotLogDao.save(log); } private FacilityTimeslot addFacilityTimeslot(FacilityItemStatusDto facilityItemStatusDto, FacilityMaster facilityMaster) { Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); FacilityTimeslot timeslot = new FacilityTimeslot(); timeslot.setBeginDatetime(facilityItemStatusDto.getBeginDatetime()); timeslot.setFacilityMaster(facilityMaster); timeslot.setEndDatetime(DateCalcUtil.GetEndTime(facilityItemStatusDto.getBeginDatetime())); timeslot.setStatus(facilityItemStatusDto.getStatus()); timeslot.setCreateBy(facilityItemStatusDto.getUpdateBy()); timeslot.setUpdateBy(facilityItemStatusDto.getUpdateBy()); timeslot.setCreateDate(new Timestamp(now.getTime())); timeslot.setUpdateDate(now); timeslot.setInternalRemark(facilityItemStatusDto.getRemark()); facilityTimeslotDao.saveOrUpdate(timeslot); return timeslot; } private void updateCourse(FacilityMasterChangeDto facilityMasterChangeDto, SimpleDateFormat sf,FacilityMaster tragetFacilityMaster,List<FacilityTimeslot> srcFacilityTimeslots) throws Exception { Long courseSessionId = 0L; List<CourseSessionFacility> srcCourseSessionFacilitys = new ArrayList<CourseSessionFacility>(); List<Long> oldTimeslotIds = new ArrayList<Long>(); String reserveType = ""; if (srcFacilityTimeslots.size() > 0) { for (FacilityTimeslot srcFacilityTimeslot : srcFacilityTimeslots) { CourseSessionFacility courseSessionFacility = courseSessionFacilityDao.getCourseSessionFacility(srcFacilityTimeslot.getFacilityTimeslotId()); if (null != courseSessionFacility) { if (courseSessionId > 0) { if (courseSessionId != courseSessionFacility.getCourseSessionId()) throw new GTACommonException(GTAError.FacilityError.BOOKING_ISNULL); } courseSessionId = courseSessionFacility.getCourseSessionId(); srcCourseSessionFacilitys.add(courseSessionFacility); oldTimeslotIds.add(srcFacilityTimeslot.getFacilityTimeslotId()); reserveType = srcFacilityTimeslot.getReserveType(); } } } if (courseSessionId > 0) { createCourseSessionFacility(facilityMasterChangeDto,courseSessionId, oldTimeslotIds,tragetFacilityMaster,FacilityStatus.TA.toString().equals(facilityMasterChangeDto.getStatus())?reserveType:Constant.RESERVE_TYPE_MT); if (srcCourseSessionFacilitys.size() > 0) { updateOldCourseSessionFacility(facilityMasterChangeDto, srcCourseSessionFacilitys); } } } private void createCourseSessionFacility(FacilityMasterChangeDto facilityMasterChangeDto,Long courseSessionId, List<Long> oldTimeslotIds,FacilityMaster tragetFacilityMaster,String reserveType) throws Exception { int j = 0; Long oldTimeslotId = 0L; Timestamp currentTimestamp= new Timestamp(Calendar.getInstance().getTimeInMillis()); for (int i = facilityMasterChangeDto.getTargetStartTime(); i <= facilityMasterChangeDto.getTargetEndTime(); i++) { String startdateStr = facilityMasterChangeDto.getTargetBookingDate() + " " + i + ":00:00"; String enddateStr = facilityMasterChangeDto.getTargetBookingDate() + " " + i + ":59:59"; FacilityTimeslot timeslot = facilityTimeslotDao.getFacilityTimeslot(tragetFacilityMaster.getFacilityNo(), DateCalcUtil.parseDateTime(startdateStr), DateCalcUtil.parseDateTime(enddateStr)); if (null == timeslot) { if (oldTimeslotIds.size() > j) oldTimeslotId = oldTimeslotIds.get(j); timeslot = createTimeslot(facilityMasterChangeDto.getUpdateBy(), DateCalcUtil.parseDateTime(startdateStr), DateCalcUtil.parseDateTime(enddateStr), tragetFacilityMaster, FacilityStatus.TA.toString().equals(facilityMasterChangeDto.getStatus())?FacilityStatus.TA.toString():FacilityStatus.OP.toString(), oldTimeslotId, currentTimestamp, reserveType); addCourseSessionFacility(facilityMasterChangeDto, courseSessionId, timeslot); if (j == 0 && !facilityMasterChangeDto.getStatus().equals(FacilityStatus.TA.toString())) { saveFacTimeslotLog(facilityMasterChangeDto, facilityMasterChangeDto.getFacilityType(), timeslot.getFacilityTimeslotId(), oldTimeslotId, reserveType); } j++; } else throw new GTACommonException(GTAError.FacilityError.FACILITYSTATUS_NOTVACANT); } } private void addCourseSessionFacility(FacilityMasterChangeDto facilityMasterChangeDto, Long courseSessionId, FacilityTimeslot timeslot) throws ParseException { CourseSessionFacility courseSessionFacility = new CourseSessionFacility(); courseSessionFacility.setCourseSessionId(courseSessionId); courseSessionFacility.setFacilityNo(timeslot.getFacilityMaster().getFacilityNo() + ""); courseSessionFacility.setFacilityTimeslot(timeslot); courseSessionFacility.setCreateBy(facilityMasterChangeDto.getUpdateBy()); courseSessionFacility.setUpdateBy(facilityMasterChangeDto.getUpdateBy()); courseSessionFacility.setCreateDate(new Timestamp(new Date().getTime())); courseSessionFacility.setUpdateDate(new Date()); courseSessionFacilityDao.save(courseSessionFacility); } private void updateOldCourseSessionFacility(FacilityMasterChangeDto changeDto, List<CourseSessionFacility> srcCourseSessionFacilitys) throws ParseException, GTACommonException { for (CourseSessionFacility oldCourseSession : srcCourseSessionFacilitys) { FacilityTimeslot timeslotOld = oldCourseSession.getFacilityTimeslot(); if (timeslotOld != null) { if(FacilityStatus.TA.name().equals(timeslotOld.getStatus())){ deleteFacilityTimeslot(timeslotOld); }else if (FacilityStatus.OP.name().equals(timeslotOld.getStatus()) || FacilityStatus.RS.name().equals(timeslotOld.getStatus())) { timeslotOld.setStatus(FacilityStatus.MT.name()); timeslotOld.setUpdateBy(changeDto.getUpdateBy()); timeslotOld.setUpdateDate(new Date()); timeslotOld.setInternalRemark(changeDto.getRemark()); facilityTimeslotDao.saveOrUpdate(timeslotOld); /*oldCourseSession.setFacilityTimeslot(null); courseSessionFacilityDao.delete(oldCourseSession);*/ } else throw new GTACommonException(GTAError.FacilityError.FACILITYSTATUS_NOTRESERVED); } else throw new GTACommonException(GTAError.FacilityError.STAFFFACILITYSCHEDULE_NOTFOUND); } } @Override @Transactional(propagation = Propagation.REQUIRED) public ResponseResult getReservationInfoByCustomerId(long customerId) { List<MemberFacilityTypeBooking> memberFacilityTypeBookingList = memberFacilityTypeBookingDao.getMemberFacilityTypeBookingByCustomerId(customerId); List<MemberFacilityTypeBooking> memberFacilityTypeBookingListSelected = new ArrayList<MemberFacilityTypeBooking>(); List<FacilityItemStatusDto> facilityItemStatusDtoList = new ArrayList<FacilityItemStatusDto>(); Map<String, Object> responseMap = new HashMap<String, Object>(); Date now = new Date(); for (MemberFacilityTypeBooking memberFacilityTypeBooking : memberFacilityTypeBookingList) { if (memberFacilityTypeBooking.getBeginDatetimeBook().after(now)) { memberFacilityTypeBookingListSelected.add(memberFacilityTypeBooking); } } for (MemberFacilityTypeBooking memberFacilityTypeBooking : memberFacilityTypeBookingListSelected) { List<MemberReservedFacility> memberReservedFacilityList = memberReservedFacilityDao.getMemberReservedFacilityList(memberFacilityTypeBooking.getResvId()); List<FacilityTimeslot> facilityTimeslotList = new ArrayList<FacilityTimeslot>(); for (MemberReservedFacility memberReservedFacility : memberReservedFacilityList) { facilityTimeslotList.add(facilityTimeslotDao.getFacilityTimeslotById(memberReservedFacility.getFacilityTimeslotId())); } for (FacilityTimeslot facilityTimeslot : facilityTimeslotList) { if (facilityTimeslot != null) { FacilityItemStatusDto facilityItemStatusDto = new FacilityItemStatusDto(); facilityItemStatusDto.setFacilityTimeslotId(facilityTimeslot.getFacilityTimeslotId()); facilityItemStatusDto.setFacilityNo((facilityTimeslot.getFacilityMaster().getFacilityNo())); facilityItemStatusDto.setFacilityName((facilityTimeslot.getFacilityMaster().getFacilityName())); facilityItemStatusDto.setBeginDatetime((facilityTimeslot.getBeginDatetime())); facilityItemStatusDto.setEndDatetime((facilityTimeslot.getEndDatetime())); facilityItemStatusDto.setBallFeedingStatus((facilityTimeslot.getFacilityTimeslotAddition() != null ? facilityTimeslot.getFacilityTimeslotAddition().getBallFeedingStatus() : "OFF")); facilityItemStatusDtoList.add(facilityItemStatusDto); } } } if (memberFacilityTypeBookingListSelected.size() > 0) { CustomerProfile customerProfile = customerProfileDao.getById(new Long(customerId)); responseMap.put("memberName", getMemberName(customerProfile.getSalutation(), customerProfile.getGivenName(), customerProfile.getSurname())); responseMap.put("beginDatetimeBook", memberFacilityTypeBookingListSelected.get(0).getBeginDatetimeBook() != null ? memberFacilityTypeBookingListSelected.get(0).getBeginDatetimeBook() : ""); responseMap.put("endDatetimeBook", memberFacilityTypeBookingListSelected.get(0).getEndDatetimeBook() != null ? memberFacilityTypeBookingListSelected.get(0).getEndDatetimeBook() : ""); responseMap.put("resvId", memberFacilityTypeBookingListSelected.get(0).getResvId()); responseMap.put("timeslots", facilityItemStatusDtoList); responseResult.initResult(GTAError.FacilityError.SUCCESS, responseMap); return responseResult; } responseResult.initResult(GTAError.FacilityError.FACILITY_NOTFOUND); return responseResult; } @Override @Transactional(propagation = Propagation.REQUIRED) public List<FacilityMasterQueryDto> getFacilityMasterList(String facilityType) { return facilityMasterDao.getFacilityMasterList(facilityType); } //Only for ball feeding machine control @Override @Transactional(propagation = Propagation.REQUIRED) public void setBallFeedingMachineStatus(List<FacilityMasterQueryDto> facilityMasterList, Map<String, String> statusMap) throws Exception { if (null == facilityMasterList) return; for (FacilityMasterQueryDto facilityMasterQueryDto: facilityMasterList) { if (statusMap.containsKey(facilityMasterQueryDto.getFactorySerialNo())){ String ballFeedingStatus = statusMap.get(facilityMasterQueryDto.getFactorySerialNo()); if (null != ballFeedingStatus && ballFeedingStatus.equals("3")) { facilityMasterQueryDto.setBallFeedingStatus("OFF"); } else if (null != ballFeedingStatus && ballFeedingStatus.equals("5")) { facilityMasterQueryDto.setBallFeedingStatus("ON"); } } } } @Override @Transactional(propagation = Propagation.REQUIRED) public int countFacilityMasterByTypeAndAttribute(String facilityType, String facilityAttribute,List<Long> facilityNos) { return facilityMasterDao.getFacilityMasterCount(facilityType, facilityAttribute,null,facilityNos); } //Only for private coaching @Override @Transactional(propagation = Propagation.REQUIRED) public List<FacilityAvailabilityDto> getFacilityAvailability(String facilityType, Date specifiedDate, String facilityAttribute) throws Exception { return getFacilityAvailabilityByFacilityNos(facilityType, specifiedDate, facilityAttribute, 1, bayNumberForPrivateCoaching(), false); } private List<Long> bayNumberForPrivateCoaching() { List<Long> facilityNos = facilityAdditionAttributeService.getFacilityAttributeFacilityNoList(Constant.ZONE_COACHING); return facilityNos; } //Only for private coaching @Override @Transactional(propagation = Propagation.REQUIRED) public List<FacilityAvailabilityDto> getFacilityAvailability(String coachId, String facilityType, Date specifiedDate,String facilityAttribute) throws Exception { List<FacilityAvailabilityDto> facilityTimeslot = getFacilityAvailabilityByFacilityNos(facilityType, specifiedDate, facilityAttribute, 1, bayNumberForPrivateCoaching(), false); DateTime dateTime = new DateTime(specifiedDate.getTime()); Date begin = dateTime.millisOfDay().withMinimumValue().toLocalDateTime().toDate(); Date end = dateTime.millisOfDay().withMaximumValue().toLocalDateTime().toDate(); Calendar cal = Calendar.getInstance(); cal.setTime(specifiedDate); final int weekday = cal.get(Calendar.DAY_OF_WEEK); final List<StaffTimeslot> staffTimeslot = staffTimeslotDao.loadStaffTimeslot(coachId, begin, end); final List<StaffCoachRoaster> coachRoster = staffCoachRoasterDao.loadOffdutyRoster(coachId, begin, end); CollectionUtil.loop(facilityTimeslot, new NoResultCallBack<FacilityAvailabilityDto>(){ @Override public void execute(FacilityAvailabilityDto t, int index) { for(StaffCoachRoaster item : coachRoster){ if(item.getOnDate() != null){ if(item.getBeginTime() == t.getHour()){ t.setAvailable(false); } } if(item.getWeekDay() != null && Integer.parseInt(item.getWeekDay()) == weekday){ if(item.getBeginTime() == t.getHour()){ t.setAvailable(false); } } } for(StaffTimeslot slot : staffTimeslot){ String hour = DateFormatUtils.format(slot.getBeginDatetime(), "HH"); if(Integer.parseInt(hour) == t.getHour()){ t.setAvailable(false); } } } }); return facilityTimeslot; } @Override @Transactional(propagation = Propagation.REQUIRED) public List<FacilityAvailabilityDto> getFacilityAvailability(String facilityType, Date specifiedDate, String facilityAttribute, int numberOfFacility, List<Long> floors) throws Exception { return this.getFacilityAvailability(facilityType, specifiedDate, facilityAttribute, numberOfFacility, floors, false); } @Override @Transactional(propagation = Propagation.REQUIRED) public List<FacilityAvailabilityDto> getFacilityAvailability(String facilityType, Date specifiedDate, String facilityAttribute, int numberOfFacility, List<Long> floors,boolean checkQuota) throws Exception { return this.getFacilityAvailabilityCommon(facilityType, specifiedDate, facilityAttribute, numberOfFacility, floors,null,false); } public List<FacilityAvailabilityDto> getFacilityAvailabilityCommon(String facilityType, Date specifiedDate, String facilityAttribute, int numberOfFacility,List<Long> floors, List<Long> facilityNos,boolean checkQuota) throws Exception { List<Date> hours = new ArrayList<Date>(); Calendar calendar = Calendar.getInstance(); calendar.setTime(specifiedDate); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); for (int i = 7; i <= 22; i++) { calendar.set(Calendar.HOUR_OF_DAY, i); hours.add(calendar.getTime()); } int facilityCount =0; List<FacilityTimeslotQueryDto> queryDtos = new ArrayList<FacilityTimeslotQueryDto>(); facilityCount = facilityMasterDao.getFacilityMasterCount(facilityType, facilityAttribute,floors,facilityNos); queryDtos = facilityTimeslotDao.getFacilityTimeslotGroupTimeCountFacilityAttribute(facilityType, hours.toArray(new Date[hours.size()]), facilityAttribute,floors,facilityNos); List<FacilityAvailabilityDto> availabilityDtoList = new ArrayList<FacilityAvailabilityDto>(); Long quota = facilityTypeQuotaService.getFacilityQuota(facilityType, calendar.getTime()); for (int i = 7; i <= 22; i++) { FacilityAvailabilityDto facilityAvailabilityDto = new FacilityAvailabilityDto(); facilityAvailabilityDto.setHour(i); if (queryDtos.get(i - 7).getFacilityCount().intValue() + numberOfFacility <= facilityCount) { if (checkQuota && null != quota && Constant.FACILITY_TYPE_GOLF.equals(facilityType)) { calendar.set(Calendar.HOUR_OF_DAY, i); boolean quotaFlag = checkMemberBookingQuota(quota,numberOfFacility,facilityType, calendar.getTime()); if (quotaFlag) facilityAvailabilityDto.setAvailable(true); else facilityAvailabilityDto.setAvailable(false); } else { facilityAvailabilityDto.setAvailable(true); } } else { facilityAvailabilityDto.setAvailable(false); } availabilityDtoList.add(facilityAvailabilityDto); } return availabilityDtoList; } private boolean checkMemberBookingQuota(Long totalQuota,int numberOfFacility,String facilityType,Date bookingDateTime) throws Exception, ParseException { if (Constant.FACILITY_TYPE_GOLF.equals(facilityType)) { int quotaResCount = memberFacilityTypeBookingDao.getMemberFacilityBookedCountForQuota(facilityType, bookingDateTime); if ((totalQuota - quotaResCount) < numberOfFacility) return false; } return true; } @Override @Transactional(propagation = Propagation.REQUIRED) public List<FacilityAvailabilityDto> getFacilityAvailability(String facilityType, Date specifiedDate, String facilityAttribute, int numberOfFacility) throws Exception { return getFacilityAvailability(facilityType, specifiedDate, facilityAttribute, numberOfFacility, null); } private void validateFacilityCondition(FacilityMasterChangeDto changeDto, SimpleDateFormat sf) throws ParseException, Exception { List<Long> facilityNos = null; if(Constant.FACILITY_TYPE_GOLF.equals(changeDto.getFacilityType())){ FacilityAdditionAttribute targetZone = facilityAdditionAttributeDao.getFacilityAdditionAttribute(changeDto.getTargetFacilityNo(), Constant.ZONE_ATTRIBUTE); facilityNos = facilityAdditionAttributeService.getFacilityAttributeFacilityNoList(targetZone.getId().getAttributeId()); } String attributeType = changeDto.getFacilityType().equalsIgnoreCase(Constant.FACILITY_TYPE_GOLF) ? Constant.GOLFBAYTYPE : Constant.TENNISCRT; FacilityAdditionAttribute attribute = facilityAdditionAttributeDao.getFacilityAdditionAttribute(changeDto.getTargetFacilityNo(), attributeType); if (null != attribute) { String attributeId = attribute.getId().getAttributeId(); int facilityCount = facilityMasterDao.getFacilityMasterCount(changeDto.getFacilityType(), attributeId,null,facilityNos); Date[] dateTimes = new Date[(changeDto.getTargetEndTime() - changeDto.getTargetStartTime()) + 1]; int time = 0; for (int i = changeDto.getTargetStartTime(); i <= changeDto.getTargetEndTime(); i++) { String startdateStr = changeDto.getTargetBookingDate() + " " + i + ":00:00"; dateTimes[time] = sf.parse(startdateStr); time++; } List<FacilityTimeslotQueryDto> queryDtos = facilityTimeslotDao.getFacilityTimeslotGroupTimeCountFacilityAttribute(changeDto.getFacilityType(), dateTimes, attributeId,null,facilityNos); if (null != queryDtos && queryDtos.size() > 0) { for (FacilityTimeslotQueryDto timeslotDto : queryDtos) { if (timeslotDto.getFacilityCount().intValue() > facilityCount) { throw new GTACommonException(GTAError.FacilityError.OPTIONAL_STADIUM_INSUFFICIENT); } } } } } @Override @Transactional public List<BayTypeDto> getFacilityBayType(String facilityType) { try{ return this.facilityMasterDao.getFacilityBayType(facilityType); }catch(Exception e){ throw new GTACommonException(GTAError.CommomError.UNHANDLED_EXCEPTION,new Object[]{e.getMessage()}); } } @Override @Transactional public FacilityMaster getFacilityMasterbyFacilityNo(Integer facilityNo){ return facilityMasterDao.get(FacilityMaster.class, facilityNo.longValue()); } @Override @Transactional public List<FacilityMaster> getFacilityByAttribute(String facilityType, String facilityAttribute) { return facilityMasterDao.getFacilityByAttribute(facilityType, facilityAttribute); } @Override @Transactional public int countFacilityMasterByTypeAndFloors(String facilityType, List<Long> floors) { return facilityMasterDao.countFacilityMasterByType(facilityType, floors,null); } /*public static List<Long> getAvailableResFacilityFloors(String facilityType) { if(!StringUtils.isEmpty(facilityType) && Constant.FACILITY_TYPE_GOLF.equals(facilityType)){ List<Long> floors = new ArrayList<Long>(); floors.add(0L); floors.add(1L); return floors; } return null; }*/ @Override @Transactional public List<FacilityItemDto> getFacilityStatusByFloorAndTime(String type, String beginDatetime, String endDatetime, Long floor) { return facilityMasterDao.getFacilityStatusByFloorAndTime(type, beginDatetime, endDatetime, floor); } @Override @Transactional public List<FacilityAvailabilityDto> getFacilityAvailabilityByFacilityNos(String facilityType, Date specifiedDate, String facilityAttribute, int numberOfFacility, List<Long> facilityNos, boolean checkQuota) throws Exception { return this.getFacilityAvailabilityCommon(facilityType, specifiedDate, facilityAttribute, numberOfFacility, null,facilityNos,checkQuota); } @Override @Transactional public int countFacilityMasterByTypeAndFacilityNos(String facilityType, List<Long> facilityNos) { return facilityMasterDao.countFacilityMasterByType(facilityType,null, facilityNos); } }
/* * MainActivity2.java * * Version: MainActivity2.java, v 1.0 2018/06/16 * * Revisions: * Revision 1.0 2018/06/16 08:11:09 * Initial Revision * */ package com.dream.the.code.droidswatch; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.graphics.Color; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TableRow.LayoutParams; import android.widget.TextView; /** * This class is the Final Result page which is displayed to the user. The final result is * displayed in User friendly language * * @author Mansha Malik * @author Parinitha Nagaraja * @author Qiaoran Li * */ public class MainActivity2 extends AppCompatActivity { // User friendly metrics string array private String[] Metrics = {"Unknown Sources Found", "Blacklisted Apps Found", "App Permission", "OS Version", "Security Patch", "Device Model", "Developer Menu Access", "Device Lock", "Boot Loader", "Root Access"}; // Device metrics private String[] MetricValues = new String[11]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); //addHeaders(); // Populates the table with results addData(); } /** * onExitClick method is called when user clicks on Done. * * param v View * * @return None */ public void onExitClick(View v) { finish(); //System.exit(0); moveTaskToBack(true); } private TextView getTextView(int id, String title, int color, int typeface, int bgColor) { TextView tv = new TextView(this); tv.setId(id); tv.setText(title.toUpperCase()); tv.setTextColor(color); tv.setPadding(20, 20, 20, 20); tv.setTypeface(Typeface.DEFAULT, typeface); tv.setBackgroundColor(bgColor); tv.setLayoutParams(getLayoutParams()); return tv; } @NonNull private LayoutParams getLayoutParams() { LayoutParams params = new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); params.setMargins(0, 0, 0, 0); return params; } @NonNull private TableLayout.LayoutParams getTblLayoutParams() { return new TableLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } /** * addHeaders method adds headers to the table. * * param None View * * @return None */ public void addHeaders() { TableLayout tl = findViewById(R.id.t1); TableRow tr = new TableRow(this); tr.setLayoutParams(getLayoutParams()); tr.addView(getTextView(0, "Metric", Color.WHITE, Typeface.NORMAL, Color.BLUE)); tr.addView(getTextView(0, "YourDeviceValues", Color.WHITE, Typeface.NORMAL, Color.BLUE)); tl.addView(tr, getTblLayoutParams()); } /** * addData method populates the table with facts * * param None View * * @return None */ public void addData() { // Get all the facts from MainActivity Bundle bundle = getIntent().getExtras(); String message = bundle.getString("message"); boolean isSensorfailed = false; // Split the facts and add it to String array MetricValues = message.split("@"); setContentView(R.layout.activity_main2); TextView mTitle = (TextView) findViewById(R.id.textView); if ( MetricValues[8].equals( Constants.SENSORDATA_NOT_AVAILABLE ) ) isSensorfailed = true; for (int i = 0; i < MetricValues.length; i++) { switch (i) { case 0: if (MetricValues[i].equals( Constants.UNKNOWN_SOURCES_ZERO )) { MetricValues[i] = Constants.ZERO; } else MetricValues[i] = Constants.MORE_THAN_ZERO; break; case 1: if (MetricValues[i].equals( Constants.BLACKLISTED_APP_ZERO )) { MetricValues[i] = Constants.ZERO; } else MetricValues[i] = Constants.MORE_THAN_ZERO; break; case 2: if (MetricValues[i].equals( Constants.APPLICATION_PERM_GOODNESS_OVER50 )) { MetricValues[i] = Constants.SAFE; } else MetricValues[i] = Constants.RISKY; break; case 3: if (MetricValues[i].equals( Constants.ANDROID_OS_VERSION_APPROVED )) { MetricValues[i] = Constants.LATEST; } else MetricValues[i] = Constants.OLD; break; case 4: if (MetricValues[i].equals( Constants.SECURITY_PATCH_DATE_APPROVED )) { MetricValues[i] = Constants.LATEST; } else MetricValues[i] = Constants.OLD; break; case 5: if (MetricValues[i].equals( Constants.DEVICE_MODEL_APPROVED )) { MetricValues[i] = Constants.INVULNERABLE; } else MetricValues[i] = Constants.VULNERABLE; break; case 6: if (MetricValues[i].equals( Constants.DEVELOPER_MENU_DISABLED )) { MetricValues[i] = Constants.DISABLED; } else MetricValues[i] = Constants.ENABLED; break; case 7: if (MetricValues[i].equals( Constants.DEVICE_LOCKED )) { MetricValues[i] = Constants.ENABLED; } else MetricValues[i] = Constants.DISABLED; break; case 8: if ( isSensorfailed ) { MetricValues[i] = Constants.DATA_UNAVAILABLE; } else if (MetricValues[i].equals( Constants.BOOTLOADER_LOCKED )) { MetricValues[i] = Constants.LOCKED; } else MetricValues[i] = Constants.UNLOCKED; break; case 9: if ( isSensorfailed ) { mTitle.setText( MetricValues[i] ); MetricValues[i] = Constants.DATA_UNAVAILABLE; } else if (MetricValues[i].equals( Constants.ROOTACCESS_DISABLED )) { MetricValues[i] = Constants.DISABLED; } else MetricValues[i] = Constants.ENABLED; break; case 10: mTitle.setText( MetricValues[i] ); break; } } // Display the 10 results in the table TableLayout Tl = findViewById(R.id.t1); for (int i = 0; i < 10; i++) { TableRow tr = new TableRow(this); tr.setLayoutParams(getLayoutParams()); tr.addView(getTextView(i + 1, Metrics[i], R.color.grey, Typeface.NORMAL, ContextCompat.getColor(this, R.color.colorAccent))); tr.addView(getTextView(i + 10, MetricValues[i], R.color.grey, Typeface.NORMAL, ContextCompat.getColor(this, R.color.colorAccent))); Tl.addView(tr, getTblLayoutParams()); } } }
package test2; import java.io.FileNotFoundException; import java.lang.SecurityException; import java.util.Formatter; import java.util.FormatterClosedException; import java.util.NoSuchElementException; import java.util.Scanner; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; public class RecordInput { private Formatter output; private InputStreamReader isr; private BufferedReader br; public RecordInput() { isr = new InputStreamReader( System.in ); br = new BufferedReader( isr ); } public void openFile( String file ) { try{ output = new Formatter( file ); } catch( FileNotFoundException e ) { e.printStackTrace(); } } public void addRecord() { Record r = new Record(); System.out.println( "Press t for terminate:" ); String name = ""; while( !name.equals( "t" ) ) { try{ name = br.readLine(); r.setName(name ); if( !name.equals( "t") ) output.format("%s\n", name ); } catch( IOException e ) { e.printStackTrace(); } } }//end of method addRecord public void closeFile() { try{ if( output != null) { output.close(); br.close(); isr.close(); }}catch( IOException e ) { } } }
public class Tienda { public float Precio; // Aca utilizamos encapsulamiento, en este hay tres tipos public, private y // protected. String Talle; String Color; int Stock; public void ActualizarStock(int i) { this.Stock = i; System.out.println("Hay Stock "+i); } public void ActualizarStock() { this.Stock = 0; System.out.println("no recibe nada"); } }
package org.yx.http.log; import javax.servlet.http.HttpServletRequest; import org.yx.http.handler.WebContext; /** * 这个在用户线程里执行,可以去到线程变量。处理最好用异步,要不然会阻塞请求,影响用户体验 */ public interface HttpLogHandler { void log(WebContext ctx); void errorLog(int code, String errorMsg, WebContext ctx); void errorLog(int code, String errorMsg, HttpServletRequest req); }
package com.tessoft.nearhere; import java.io.IOException; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.type.TypeReference; import com.tessoft.common.Constants; import com.tessoft.nearhere.adapters.SettingsAdapter; import com.tessoft.domain.APIResponse; import com.tessoft.domain.SettingListItem; import com.tessoft.domain.User; import com.tessoft.domain.UserSetting; import com.tessoft.nearhere.fragments.BaseListFragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; public class SettingsFragment extends BaseListFragment { SettingsAdapter adapter = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub try { super.onCreateView(inflater, container, savedInstanceState); listMain = (ListView) rootView.findViewById(R.id.listMain); adapter = new SettingsAdapter(getActivity(), this, 0); SettingListItem setting = new SettingListItem(); setting.setSettingName("쪽지알림받기"); setting.setSettingValue("Y"); adapter.add(setting); setting = new SettingListItem(); setting.setSettingName("댓글알림받기"); setting.setSettingValue("Y"); adapter.add(setting); setting = new SettingListItem(); setting.setSettingName("추천알림받기"); setting.setSettingValue("Y"); adapter.add(setting); setting = new SettingListItem(); setting.setSettingName("프로필 조회 알림받기"); setting.setSettingValue("Y"); adapter.add(setting); setting = new SettingListItem(); setting.setSettingName("신규회원 알림받기"); setting.setSettingValue("Y"); adapter.add(setting); listMain.setAdapter(adapter); inquirySettingInfo(); Button btnRefresh = (Button) rootView.findViewById(R.id.btnRefresh); btnRefresh.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub try { inquirySettingInfo(); } catch ( Exception ex ) { // TODO Auto-generated catch block catchException(this, ex); } } }); setTitle("설정"); } catch( Exception ex ) { catchException(this, ex); } return rootView; } private void inquirySettingInfo() throws IOException, JsonGenerationException, JsonMappingException { User user = application.getLoginUser(); rootView.findViewById(R.id.marker_progress).setVisibility(ViewGroup.VISIBLE); listMain.setVisibility(ViewGroup.GONE); sendHttp("/taxi/getUserSetting.do", mapper.writeValueAsString(user), 1 ); } @Override public void doPostTransaction(int requestCode, Object result) { // TODO Auto-generated method stub try { rootView.findViewById(R.id.marker_progress).setVisibility(ViewGroup.GONE); if ( Constants.FAIL.equals(result) ) { showOKDialog("통신중 오류가 발생했습니다.\r\n다시 시도해 주십시오.", null); return; } listMain.setVisibility(ViewGroup.VISIBLE); super.doPostTransaction(requestCode, result); APIResponse response = mapper.readValue(result.toString(), new TypeReference<APIResponse>(){}); if ( "0000".equals( response.getResCode() ) ) { if ( requestCode == 1 ) { String settingString = mapper.writeValueAsString( response.getData() ); UserSetting setting = mapper.readValue( settingString , new TypeReference<UserSetting>(){}); if ( setting == null ) { setting = new UserSetting(); setting.setMessagePushReceiveYN("Y"); setting.setReplyPushReceiveYN("Y"); setting.setRecommendPushReceiveYN("Y"); setting.setInquiryUserPushReceiveYN("Y"); setting.setNewUserPushReceiveYN("Y"); } for ( int i = 0; i < adapter.getCount(); i++ ) { SettingListItem item = adapter.getItem(i); if ("쪽지알림받기".equals( item.getSettingName() )) item.setSettingValue( setting.getMessagePushReceiveYN() ); else if ("댓글알림받기".equals( item.getSettingName() )) item.setSettingValue( setting.getReplyPushReceiveYN() ); else if ("추천알림받기".equals( item.getSettingName() )) item.setSettingValue( setting.getRecommendPushReceiveYN() ); else if ("프로필 조회 알림받기".equals( item.getSettingName() )) item.setSettingValue( setting.getInquiryUserPushReceiveYN() ); else if ("신규회원 알림받기".equals( item.getSettingName() )) item.setSettingValue( setting.getNewUserPushReceiveYN() ); } adapter.notifyDataSetChanged(); } } else { showOKDialog("경고", response.getResMsg(), null); return; } } catch( Exception ex ) { catchException(this, ex); } } @Override public void doAction(String actionName, Object param) { // TODO Auto-generated method stub try { super.doAction(actionName, param); UserSetting setting = new UserSetting(); setting.setUserID( application.getLoginUser().getUserID() ); for ( int i = 0; i < adapter.getCount(); i++ ) { SettingListItem item = adapter.getItem(i); if ("쪽지알림받기".equals( item.getSettingName() )) setting.setMessagePushReceiveYN( item.getSettingValue() ); else if ("댓글알림받기".equals( item.getSettingName() )) setting.setReplyPushReceiveYN(item.getSettingValue() ); else if ("추천알림받기".equals( item.getSettingName() )) setting.setRecommendPushReceiveYN(item.getSettingValue() ); else if ("프로필 조회 알림받기".equals( item.getSettingName() )) setting.setInquiryUserPushReceiveYN(item.getSettingValue() ); else if ("신규회원 알림받기".equals( item.getSettingName() )) setting.setNewUserPushReceiveYN( item.getSettingValue() ); } getActivity().setProgressBarIndeterminateVisibility(true); sendHttp("/taxi/updateUserSetting.do", mapper.writeValueAsString( setting ), 2); } catch( Exception ex ) { catchException(this, ex); } } //This is the handler that will manager to process the broadcast intent private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { try { inquirySettingInfo(); } catch( Exception ex ) { catchException(this, ex); } } }; @Override public void onStart() { // TODO Auto-generated method stub super.onStart(); getActivity().registerReceiver(mMessageReceiver, new IntentFilter("refreshContents")); } @Override public void onStop() { // TODO Auto-generated method stub super.onStop(); getActivity().unregisterReceiver(mMessageReceiver); } }
package ru.client.view.tablemodel; import ru.client.Observable; import ru.client.Observer; import ru.client.model.Workshops; import ru.client.model.WorkshopsDAO; import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; import java.util.ArrayList; import java.util.List; public class WorkshopsTableModel implements TableModel, Observable { private List<Workshops> workshopsList; private final WorkshopsDAO workshopsDAO; private List<Observer> observers; public WorkshopsTableModel(List<Workshops> workshopsList, WorkshopsDAO workshopsDAO) { this.workshopsList = workshopsList; this.workshopsDAO = workshopsDAO; observers = new ArrayList<>(); } @Override public int getRowCount() { return workshopsList.size(); } @Override public int getColumnCount() { return 2; } @Override public String getColumnName(int columnIndex) { switch (columnIndex) { case 0: return "id"; case 1: return "Название"; } return null; } @Override public Class<?> getColumnClass(int columnIndex) { switch (columnIndex) { case 0: return Integer.class; case 1: return String.class; default: return null; } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { switch (columnIndex) { case 1: return true; default: return false; } } @Override public Object getValueAt(int rowIndex, int columnIndex) { Workshops workshops = workshopsList.get(rowIndex); switch (columnIndex) { case 0: return workshops.getId(); case 1: return workshops.getName(); default: return null; } } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { Workshops workshops = workshopsList.get(rowIndex); switch (columnIndex) { case 1: String name = (String) aValue; workshops.setName(name); workshopsDAO.update(workshops); observers.stream().forEach(Observer::update); break; } } @Override public void addTableModelListener(TableModelListener l) {} @Override public void removeTableModelListener(TableModelListener l) {} @Override public void addListener(Observer observer) { observers.add(observer); } @Override public void removeListener(Observer observer) { observers.remove(observer); } }
package com.melodygram.activity; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.app.ShareCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.android.volley.NoConnectionError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.melodygram.R; import com.melodygram.constants.APIConstant; import com.melodygram.constants.GlobalState; import com.melodygram.singleton.AppController; import com.melodygram.utils.CommonUtil; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.RequestBody; public class ProfileActivity extends Activity implements View.OnClickListener { private ImageView statusEditButton, userNameEditButton, profileImage, inviteButton, facebookButton, tweeterButton, googleButton, linkedinButton, emailButton, msgButton; private RelativeLayout galleryButton, cameraButton, existingPhotoButton, removePhotoButton; private Activity activity; private boolean socialNtkVisiblity; private boolean profileEditFlag; private EditText userNameText, statusText; private AppController appController; private boolean isStatusNameChanges; private TextView phoneNumber; private String profilePic; ImageView profile_image_edit; private File cameraFile; RelativeLayout header_back_button_parent; ImageView musicDownload; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); setContentView(R.layout.activity_profile); activity = this; initialization(); } private void initialization() { appController = AppController.getInstance(); header_back_button_parent=(RelativeLayout)findViewById(R.id.header_back_button_parent); header_back_button_parent.setOnClickListener(this); musicDownload = (ImageView) findViewById(R.id.settings_button_image); profileImage = (ImageView)findViewById(R.id.profile_image); profileImage.setOnClickListener(this); facebookButton = (ImageView) findViewById(R.id.facebook_button); facebookButton.setOnClickListener(this); tweeterButton = (ImageView) findViewById(R.id.tweeter_button); tweeterButton.setOnClickListener(this); linkedinButton = (ImageView)findViewById(R.id.more_button); linkedinButton.setOnClickListener(this); googleButton = (ImageView) findViewById(R.id.google_button); googleButton.setOnClickListener(this); emailButton = (ImageView) findViewById(R.id.mail_button); emailButton.setOnClickListener(this); msgButton = (ImageView) findViewById(R.id.msg_button); msgButton.setOnClickListener(this); inviteButton = (ImageView) findViewById(R.id.invite_button); inviteButton.setOnClickListener(this); galleryButton = (RelativeLayout) findViewById(R.id.gallery_icon_parent); galleryButton.setOnClickListener(this); cameraButton = (RelativeLayout) findViewById(R.id.take_photo_parent); cameraButton.setOnClickListener(this); existingPhotoButton = (RelativeLayout) findViewById(R.id.existing_photo_parent); existingPhotoButton.setOnClickListener(this); removePhotoButton = (RelativeLayout) findViewById(R.id.remove_photo_parent); removePhotoButton.setOnClickListener(this); userNameText = (EditText) findViewById(R.id.name_edit_text); statusText = (EditText) findViewById(R.id.status_edit_text); userNameEditButton = (ImageView) findViewById(R.id.user_name_edit); userNameEditButton.setOnClickListener(this); statusEditButton = (ImageView) findViewById(R.id.status_edit); statusEditButton.setOnClickListener(this); phoneNumber = (TextView) findViewById(R.id.phone_number); profile_image_edit=(ImageView)findViewById(R.id.profile_image_edit); profile_image_edit.setOnClickListener(this); // view.findViewById(R.id.profile_image_edit).setOnClickListener(this); findViewById(R.id.options_parent).setOnClickListener(this); musicDownload.setVisibility(View.GONE); intitView(); } private void intitView() { HashMap<String, String> map = appController.getUserDetails(); profilePic = map.get("pic"); String status = map.get("status"); String profileName = map.get("profile_name"); String phone = map.get("mobile"); String code = map.get("country_code"); if (profilePic.length() > 0) appController.displayUrlImage(profileImage, profilePic, null); if (status.length() > 0) statusText.setText(status); if (profileName.length() > 0) userNameText.setText(profileName); phoneNumber.setText("+" + code + phone); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.profile_image: Intent intent = new Intent(activity, PicViewerActivity.class); intent.putExtra("imageURL", profilePic); activity.startActivity(intent); break; case R.id.profile_image_edit: profilePicVisiblity(); break; case R.id.options_parent: if (profileEditFlag) { galleryButton.setVisibility(View.GONE); cameraButton.setVisibility(View.GONE); existingPhotoButton.setVisibility(View.GONE); removePhotoButton.setVisibility(View.GONE); profile_image_edit.setVisibility(View.VISIBLE); profileEditFlag = false; } break; case R.id.invite_button: setSocialNtkVisiblity(); break; case R.id.facebook_button: facebookshare(); setSocialNtkVisiblity(); break; case R.id.tweeter_button: tweeterShare(); setSocialNtkVisiblity(); break; case R.id.more_button: moreShare(); setSocialNtkVisiblity(); break; /* case R.id.linkedin_button: linkedinShare(); setSocialNtkVisiblity(); break;*/ case R.id.google_button: googlePlusShare(); setSocialNtkVisiblity(); break; case R.id.mail_button: mailShare(); setSocialNtkVisiblity(); break; case R.id.msg_button: msgShare(); setSocialNtkVisiblity(); break; case R.id.gallery_icon_parent: profilePicVisiblity(); openGallery(); break; case R.id.existing_photo_parent: profilePicVisiblity(); pickExistingImage(); break; case R.id.remove_photo_parent: profilePicVisiblity(); // removeUserPic(); break; case R.id.take_photo_parent: profilePicVisiblity(); openCamera(); break; case R.id.user_name_edit: userNameText.setClickable(true); userNameText.setCursorVisible(true); userNameText.setFocusable(true); isStatusNameChanges = true; break; case R.id.status_edit: statusText.setClickable(true); statusText.setFocusable(true); statusText.setCursorVisible(true); isStatusNameChanges = true; showDialog(); break; case R.id. header_back_button_parent: finish(); break; } } private void setSocialNtkVisiblity() { if (socialNtkVisiblity) { facebookButton.setVisibility(View.GONE); tweeterButton.setVisibility(View.GONE); googleButton.setVisibility(View.GONE); linkedinButton.setVisibility(View.GONE); emailButton.setVisibility(View.GONE); msgButton.setVisibility(View.GONE); socialNtkVisiblity = false; } else { facebookButton.setVisibility(View.VISIBLE); tweeterButton.setVisibility(View.VISIBLE); googleButton.setVisibility(View.VISIBLE); linkedinButton.setVisibility(View.VISIBLE); emailButton.setVisibility(View.VISIBLE); msgButton.setVisibility(View.VISIBLE); socialNtkVisiblity = true; } } private void profilePicVisiblity() { if (profileEditFlag) { galleryButton.setVisibility(View.GONE); cameraButton.setVisibility(View.GONE); existingPhotoButton.setVisibility(View.GONE); removePhotoButton.setVisibility(View.GONE); profile_image_edit.setVisibility(View.VISIBLE); profileEditFlag = false; } else { galleryButton.setVisibility(View.VISIBLE); cameraButton.setVisibility(View.VISIBLE); existingPhotoButton.setVisibility(View.VISIBLE); removePhotoButton.setVisibility(View.VISIBLE); profile_image_edit.setVisibility(View.GONE); profileEditFlag = true; } } private void facebookshare() { try { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_name)); intent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.share_msg)); boolean facebookAppFound = false; List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0); for (ResolveInfo info : matches) { if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana")) { intent.setPackage(info.activityInfo.packageName); facebookAppFound = true; break; } } if (!facebookAppFound) { String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + getResources().getString(R.string.share_msg); intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl)); } startActivity(intent); } catch (Exception e) { Intent intent = new Intent(Intent.ACTION_SEND); String sharerUrl = "https://play.google.com/store/apps/details?id=com.facebook.katana&hl=en" + getResources().getString(R.string.share_msg); intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl)); startActivity(intent); } } private void tweeterShare() { Intent tweetIntent = new Intent(Intent.ACTION_SEND); tweetIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_name)); tweetIntent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.share_msg)); tweetIntent.setType("text/plain"); PackageManager packManager = getPackageManager(); List<ResolveInfo> resolvedInfoList = packManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY); boolean resolved = false; for (ResolveInfo resolveInfo : resolvedInfoList) { if (resolveInfo.activityInfo.packageName.startsWith("com.twitter.android")) { tweetIntent.setClassName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name); resolved = true; break; } } if (resolved) { startActivity(tweetIntent); } else { Toast.makeText(activity, getResources().getString(R.string.app_not_found), Toast.LENGTH_SHORT).show(); } } private void googlePlusShare() { if(isGooglePlusInstalled()) { Intent shareIntent = ShareCompat.IntentBuilder.from(activity) .setType("text/plain") .setText(getResources().getString(R.string.share_msg)) .setStream(null) .getIntent() .setPackage("com.google.android.apps.plus"); startActivity(shareIntent); }else { Toast.makeText(activity, getResources().getString(R.string.app_not_found), Toast.LENGTH_SHORT).show(); } } public static void filterByPackageName(Context context, Intent intent, String prefix) { List<ResolveInfo> matches = context.getPackageManager().queryIntentActivities(intent, 0); for (ResolveInfo info : matches) { if (info.activityInfo.packageName.toLowerCase().startsWith(prefix)) { intent.setPackage(info.activityInfo.packageName); return; } } } private void linkedinShare() { try { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_name)); shareIntent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.share_msg)); List<ResolveInfo> matches = getPackageManager() .queryIntentActivities(shareIntent, 0); for (ResolveInfo info : matches) { if (info.activityInfo.packageName.toLowerCase().startsWith( "com.linkedin")) { shareIntent.setPackage(info.activityInfo.packageName); break; } } startActivity(shareIntent); } catch (ActivityNotFoundException e) { Toast.makeText(activity, getResources().getString(R.string.app_not_found), Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } private void mailShare() { try { Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.setType("plain/text"); sendIntent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail"); sendIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_name)); sendIntent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.share_msg)); startActivity(sendIntent); } catch (Exception e) { e.printStackTrace(); } } private void msgShare() { String urlToShare = getResources().getString(R.string.share_msg); try { Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra("sms_body", urlToShare); sendIntent.setType("vnd.android-dir/mms-sms"); startActivity(sendIntent); } catch (Exception e) { e.printStackTrace(); } } private void moreShare() { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.share_msg)); sendIntent.setType("text/plain"); startActivity(sendIntent); // Intent sharingIntent = new Intent(Intent.ACTION_SEND); // sharingIntent.setType("text/html"); // sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, getResources().getString(R.string.share_msg)); // startActivity(Intent.createChooser(sharingIntent, "Share using")); } private void openCamera() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { imageFromCamera(); } else { requestPermissions( new String[]{Manifest.permission.CAMERA}, GlobalState.CAMERA_REQUEST); } } else { imageFromCamera(); } } private void openGallery() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { imageFromGallery(); } else { requestPermissions( new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, GlobalState.READ_EXTERNAL_STORAGE); } } else { imageFromGallery(); } } private void imageFromGallery() { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, GlobalState.IMAGE_FROM_GALLERY); } private void imageFromCamera() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); cameraFile = getCaptureImagePath(); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)); startActivityForResult(intent, GlobalState.CAMERA_REQUEST); } else { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, }, GlobalState.WRITE_PERMISSIONS); } } else { Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); cameraFile = getCaptureImagePath(); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)); startActivityForResult(intent, GlobalState.CAMERA_REQUEST); } } private void pickExistingImage() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { } else { requestPermissions( new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, GlobalState.READ_EXTERNAL_STORAGE_FOLDER); } } else { initExistingImageDialog(); } } private void initExistingImageDialog() { Intent intent = new Intent(activity, ChooseFolderActivity.class); startActivityForResult(intent, GlobalState.EXISTING_FOLDER); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case GlobalState.CAMERA_REQUEST: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { imageFromCamera(); } else { Toast.makeText(activity, getResources().getString(R.string.permission_not_granted), Toast.LENGTH_SHORT).show(); } break; case GlobalState.READ_EXTERNAL_STORAGE: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { imageFromGallery(); } else { Toast.makeText(activity, getResources().getString(R.string.permission_not_granted), Toast.LENGTH_SHORT).show(); } break; case GlobalState.READ_EXTERNAL_STORAGE_FOLDER: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { initExistingImageDialog(); } else { Toast.makeText(activity, getResources().getString(R.string.permission_not_granted), Toast.LENGTH_SHORT).show(); } break; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Uri imageUri; if (resultCode == AppCompatActivity.RESULT_OK) { switch (requestCode) { case GlobalState.IMAGE_FROM_GALLERY: imageUri = data.getData(); if (imageUri != null) { String imagePath = CommonUtil.compressProfileImage(CommonUtil.getRealPathFromURI(imageUri, activity), "midQuality"); Bitmap bitmap = BitmapFactory.decodeFile(imagePath); if (bitmap != null) { profileImage.setImageBitmap(bitmap); } updateProfilePic(imagePath); break; } case GlobalState.CAMERA_REQUEST: String cameraPic = cameraFile.getAbsolutePath(); AppController.getInstance().displayFileImage(profileImage, cameraPic, null); updateProfilePic(cameraPic); break; case GlobalState.EXISTING_FOLDER: String path = data.getExtras().getString("path"); AppController.getInstance().displayFileImage(profileImage, path, null); updateProfilePic(path); break; case GlobalState.WRITE_PERMISSIONS: Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); cameraFile = getCaptureImagePath(); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)); startActivityForResult(intent, GlobalState.CAMERA_REQUEST); break; } } } private void updateProfilePic(String path) { new UpdatePic().execute(path); } private void startCropImage() { // Intent intent = new Intent(getActivity(), CropImage.class); // intent.putExtra(CropImage.IMAGE_PATH, mFileTemp.getPath()); // intent.putExtra(CropImage.SCALE, true); // // intent.putExtra(CropImage.ASPECT_X, 3); // intent.putExtra(CropImage.ASPECT_Y, 2); // // startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE); } public void updateStatusUserName() { if (isStatusNameChanges) { JSONObject objJson = new JSONObject(); try { objJson.accumulate("profile_name", userNameText.getText().toString()); objJson.accumulate("status", statusText.getText().toString()); objJson.accumulate("user_id", appController.getUserId()); objJson.accumulate("profilepic", ""); } catch (JSONException e) { e.printStackTrace(); } Log.v("Login REQUEST", objJson.toString()); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, APIConstant.UPDATE_PROFILE, objJson, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.v("Login response", response.toString()); if (response != null) { parseServerResponse(response); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error instanceof NoConnectionError) { Toast.makeText(activity, getString(R.string.no_internet_connection), Toast.LENGTH_SHORT).show(); } else if (error instanceof TimeoutError) { Toast.makeText(activity, getString(R.string.pic_upload_failed), Toast.LENGTH_SHORT).show(); } } }); AppController.getInstance().addToRequestQueue(jsonObjReq); isStatusNameChanges = false; } } public void removeUserPic() { JSONObject objJson = new JSONObject(); try { objJson.accumulate("user_id", appController.getUserId()); objJson.accumulate("pic", "uploads/no_image_found.png"); } catch (JSONException e) { e.printStackTrace(); } final Dialog dialog = appController.getLoaderDialog(activity); dialog.show(); Log.v("REQUEST", objJson.toString()); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, APIConstant.UPDATE_PROFILE, objJson, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { if (dialog.isShowing()) dialog.dismiss(); Log.v("response", response.toString()); if (response != null) { try { if (response != null) { SharedPreferences sharedPreferences = AppController.getInstance().getPrefs(); SharedPreferences.Editor editor = sharedPreferences.edit(); if (response.getString("status").equalsIgnoreCase("success")) { JSONObject resultObj = response.getJSONObject("Result"); String pic = resultObj.getString("pic"); if (pic.length() > 0) appController.displayUrlImage(profileImage, pic, null); appController.getPrefs().edit().putString("pic", pic).commit(); editor.commit(); } } } catch (JSONException e) { e.printStackTrace(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (dialog.isShowing()) dialog.dismiss(); if (error instanceof NoConnectionError) { Toast.makeText(activity, getString(R.string.no_internet_connection), Toast.LENGTH_SHORT).show(); } else if (error instanceof TimeoutError) { Toast.makeText(activity, getString(R.string.server_error), Toast.LENGTH_SHORT).show(); } } }); AppController.getInstance().addToRequestQueue(jsonObjReq); } private void parseServerResponse(JSONObject response) { try { if (response != null) { SharedPreferences sharedPreferences = AppController.getInstance().getPrefs(); SharedPreferences.Editor editor = sharedPreferences.edit(); if (response.getString("status").equalsIgnoreCase("success")) { JSONObject resultObj = response.getJSONObject("Result"); editor.putString("profile_name", resultObj.getString("profile_name")); editor.putString("status", resultObj.getString("status")); editor.commit(); } } } catch (JSONException e) { e.printStackTrace(); } } class UpdatePic extends AsyncTask<String, Void, String> { Dialog dialog; MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); OkHttpClient client = new OkHttpClient(); @Override protected void onPreExecute() { super.onPreExecute(); dialog = appController.getLoaderDialog(activity); dialog.show(); } @Override protected String doInBackground(String... params) { String result = null; try { RequestBody requestBody; MultipartBody.Builder body; okhttp3.Request request; body = new MultipartBody.Builder(); body.setType(MultipartBody.FORM); body.addFormDataPart("user_id", appController.getUserId()); body.addFormDataPart("pic", "pic", RequestBody.create(MEDIA_TYPE_PNG, new File(params[0]))); requestBody = body.build(); request = new okhttp3.Request.Builder() .url(APIConstant.UPDATE_PROFILE_PIC) .post(requestBody) .build(); okhttp3.Response response = client.newCall(request).execute(); result = response.body().string(); } catch (Exception e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } try { if (result != null) { JSONObject json = new JSONObject(result); if (json != null && json.optString("status").equalsIgnoreCase("success")) { Toast.makeText(activity, getString(R.string.profile_pic_updated), Toast.LENGTH_SHORT).show(); JSONObject resultObj = json.getJSONObject("Result"); appController.getPrefs().edit().putString("pic", resultObj.getString("pic")).commit(); } else { Toast.makeText(activity, getString(R.string.server_error), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(activity, getString(R.string.server_error), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } } public boolean isGooglePlusInstalled() { try { getPackageManager().getApplicationInfo("com.google.android.apps.plus", 0); return true; } catch(PackageManager.NameNotFoundException e) { return false; } } private File getCaptureImagePath() { File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), GlobalState.POST_TEMP_PICTURE); if (!mediaStorageDir.exists()) { mediaStorageDir.mkdirs(); } String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".png"); return mediaFile; } public void showDialog(){ LayoutInflater factory = LayoutInflater.from(activity); final View dialogView = factory.inflate( R.layout.activity_status, null); final AlertDialog dialog = new AlertDialog.Builder(activity).create(); dialog.setView(dialogView); ArrayAdapter adapter = new ArrayAdapter<String>(activity, R.layout.item_status_layout, getResources().getStringArray(R.array.status_array)); ListView listView=(ListView)dialogView.findViewById(R.id.listViewId); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String selectedStatus = parent.getItemAtPosition(position).toString(); statusText.setText(selectedStatus); dialog.dismiss(); } }); dialog.show(); } }
/* * Origin of the benchmark: * repo: https://github.com/diffblue/cbmc.git * branch: develop * directory: regression/cbmc-java/basic1 * The benchmark was taken from the repo: 24 January 2018 */ // from // http://www.thegeekstuff.com/2010/02/java-hello-world-example-how-to-write-and-execute-java-program-on-unix-os/ /* Hello World Java Program */ class Main { public static void main(String[] args) { assert(System.out != null); System.out.println("Hello World!"); assert(System.err != null); System.err.println("Hello World!"); assert(System.in != null); try { int avail = System.in.available(); } catch(java.io.IOException e) {} } }
package com.innominds.controller; import java.util.List; import java.lang.String; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.cloudant.client.api.model.IndexField; import com.cloudant.client.api.model.IndexField.SortOrder; import com.cloudant.client.api.model.Response; import com.innominds.db.CloudantDB; import com.innominds.dto.PersonDTO; @RestController public class PersonController { @Autowired private CloudantDB cloudantDB; @RequestMapping(value = "/details", method = RequestMethod.POST, consumes = "application/json") public @ResponseBody String saveData(@RequestBody PersonDTO personDetails) { // cloudantDB.getDB().save(personDetails); // PersonDTO create=(PersonDTO) cloudantDB.getDB().find(PersonDTO.class, // "35073b9d83a94d059b8b57dc1bbdb3fc"); // return create.toString(); // System.out.println("save data " + person); Response r = null; if (personDetails != null) { r = cloudantDB.getDB().post(personDetails); } System.out.println("save data " + personDetails); return r.getId(); } @RequestMapping(method = RequestMethod.GET) public @ResponseBody List getAll(@RequestParam(required = false) String id) { List allDocs = null; try { if (id == null) { allDocs = cloudantDB.getDB().getAllDocsRequestBuilder().includeDocs(true).build().getResponse() .getDocsAs(PersonDTO.class); } else { cloudantDB.getDB().createIndex("personview", "persondoc", "javascript", new IndexField[] { new IndexField("id", SortOrder.asc) }); System.out.println("Successfully created index"); allDocs = cloudantDB.getDB().findByIndex("{\"id\" : " + id + "}", PersonDTO.class); } } catch (Exception e) { System.out.println("Exception thrown : " + e.getMessage()); } return allDocs; } @RequestMapping(method = RequestMethod.PUT) public Response updatePerson(@RequestParam(required = false) String id, @RequestBody PersonDTO personDTO) { PersonDTO update = cloudantDB.getDB().find(PersonDTO.class, "person123"); //update.setId(personDTO.getId()); update.setName(personDTO.getName()); update.setAge(personDTO.getAge()); update.setRev(personDTO.getRev()); return cloudantDB.getDB().update(update); } @RequestMapping(method = RequestMethod.DELETE) public Response deletePerson(@RequestParam(required = false) String id, @RequestBody PersonDTO personDTO){ PersonDTO delete = cloudantDB.getDB().find(PersonDTO.class, "person123"); return cloudantDB.getDB().remove(delete); } }
package com.javarush.task.task18.task1823; import java.io.*; import java.util.HashMap; import java.util.Map; /* Нити и байты */ public class Solution { public static Map<String, Integer> resultMap = new HashMap<String, Integer>(); public static void main(String[] args) throws IOException, InterruptedException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while(true){ String fileName = reader.readLine(); if(fileName.equals("exit")){ return; } new ReadThread(fileName).start(); } } public static class ReadThread extends Thread { private final String fileName; public ReadThread(String fileName) { this.fileName = fileName; } @Override public void run() { int[] array = new int[256]; try(FileInputStream fileInputStream = new FileInputStream(fileName)) { while(fileInputStream.available() > 0){ int data = fileInputStream.read(); array[data]++; } } catch (IOException e) { e.printStackTrace(); } int max = Integer.MIN_VALUE; int bytes = 0; for (int i = 0; i < array.length; i++) { if(array[i] > max){ max = array[i]; bytes = i; } } resultMap.put(fileName, bytes); System.out.println(fileName + " " + bytes); } } }
package com.bnebit.sms.service; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.servlet.ModelAndView; import com.bnebit.sms.dao.ChartDAO; import com.bnebit.sms.dao.EmployeeDAO; import com.bnebit.sms.vo.Chart; import com.bnebit.sms.vo.Employee; @Service public class ChartService { @Autowired private ChartDAO chartDAO; @Autowired private EmployeeDAO employeeDAO; @Autowired private ModelAndView mav; // 매출 달성율 차트 public ModelAndView profitRateChart(HttpSession session, String chartType, String type, String empId) throws SQLException { Employee employee=(Employee)session.getAttribute("LOGIN_USER"); Map<String, Object> paramMap = new HashMap<String, Object>(); if("Manager".equals(employee.getPosition())){ paramMap.put("chartType", chartType); if("1".equals(chartType)){ paramMap.put("deptId", employee.getDept().getDeptId()); }else if("2".equals(chartType)){ paramMap.put("empId", empId); } }else{ paramMap.put("chartType", "2"); paramMap.put("empId", employee.getEmpId()); } paramMap.put("key", type); ArrayList<Chart> profitRateList = (ArrayList<Chart>) chartDAO.profitRateChart(paramMap); mav.addObject("JSON",profitRateList); mav.setViewName("jsonView"); return mav; } // 매출액, 매출목표 차트 public ModelAndView profitChart(HttpSession session, String chartType, String type, String empId) throws SQLException { Employee employee=(Employee)session.getAttribute("LOGIN_USER"); Map<String, Object> paramMap = new HashMap<String, Object>(); if("Manager".equals(employee.getPosition())){ paramMap.put("chartType", chartType); if("1".equals(chartType)){ paramMap.put("deptId", employee.getDept().getDeptId()); }else if("2".equals(chartType)){ paramMap.put("empId", empId); } }else{ paramMap.put("chartType", "2"); paramMap.put("empId", employee.getEmpId()); } paramMap.put("key", type); ArrayList<Chart> salesGoalList=(ArrayList<Chart>) chartDAO.salesGoalChart(paramMap); ArrayList<Chart> profitList = (ArrayList<Chart>) chartDAO.profitChart(paramMap); HashMap<String, ArrayList<Chart>> map=new HashMap<String, ArrayList<Chart>> (); map.put("SalesGoal", salesGoalList); map.put("Profit", profitList); mav.addObject("JSON",map); mav.setViewName("jsonView"); return mav; } // 주행거리 차트 public ModelAndView distanceChart(HttpSession session, String chartType, String type, String empId) throws SQLException { Employee employee=(Employee) session.getAttribute("LOGIN_USER"); Map<String, Object> paramMap = new HashMap<String, Object>(); if("Manager".equals(employee.getPosition())){ paramMap.put("chartType", chartType); if("1".equals(chartType)){ paramMap.put("deptId", employee.getDept().getDeptId()); }else if("2".equals(chartType)){ paramMap.put("empId", empId); } }else{ paramMap.put("chartType", "2"); paramMap.put("empId", employee.getEmpId()); } paramMap.put("key", type); ArrayList<Chart> distanceList = (ArrayList<Chart>) chartDAO.distanceChart(paramMap); mav.addObject("JSON", distanceList); mav.setViewName("jsonView"); return mav; } // 부서에 속하는 모든 empName 불러오기 public ModelAndView selectEmployeeByDept(HttpSession session) throws Exception{ Employee employee=(Employee) session.getAttribute("LOGIN_USER"); ArrayList<Employee>empList=employeeDAO.selectEmployeeByDept(employee.getDept().getDeptId()); mav.addObject("JSON", empList); mav.setViewName("jsonView"); return mav; } public ModelAndView viewChart(HttpSession session) throws Exception{ Employee employee=(Employee) session.getAttribute("LOGIN_USER"); if("Manager".equals(employee.getPosition())){ mav.setViewName("chart/viewChartManager"); }else{ mav.setViewName("chart/viewChart"); } return mav; } }
package aaa.assignment1.tests; import aaa.Agent; import aaa.PreySimple; import aaa.Simulator; import aaa.State; import aaa.StateSimple; import aaa.assignment1.algorithms.ValueIteration; /** * TEST 5 (Assignment 1.4) * This test calculates the optimal policy using the Value Iteration algorithm and then runs and displays a simulation to check the behaviour of the optimal agent. * When the game is finished, the number of turns elapsed are displayed. * @author josago */ public class Test5 { public static final float THETA = 0.000000001f; public static final float GAMMA = 0.9f; public static void main(String[] args) { State stateInitial = new StateSimple(0, 0, 5, 5); Agent prey = new PreySimple(); ValueIteration vi = new ValueIteration(stateInitial, prey, THETA, GAMMA); Agent predator = vi.buildAgent(); int turns = Simulator.runSimulation(stateInitial, prey, predator, 250, true); System.out.println("The predator catched the prey in " + turns + " turns."); } }
package com.vaadin.vaadin_archetype_application; import java.time.Instant; import java.time.Year; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAmount; import java.util.Date; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.AbstractOrderedLayout; import com.vaadin.ui.Button; import com.vaadin.ui.DateField; import com.vaadin.ui.GridLayout; import com.vaadin.ui.Label; import com.vaadin.ui.PasswordField; import com.vaadin.ui.TextField; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; public class CreateMeetingView extends ILoggedInView { private TextField tbMeetingName; //private TextField tbMeetingCreatorEmailAddress; //private TextField tbMeetingParticipantEmailAddresses; private DateField tbMeetingStartDate; private DateField tbMeetingEndDate; private TextField tbMeetingDuration; private PasswordField tbMeetingPassword; private PasswordField tbConfirmMeetingPassword; private Label lErrorMessage; @Override public String GetPageTitle() { return "Create Meeting"; } @Override public String GetPageURL() { return Constants.URL_CREATE_MEETING; } @Override protected AbstractOrderedLayout InitUI() { tbMeetingName = new TextField(); tbMeetingStartDate = new DateField(); tbMeetingStartDate.setResolution(DateField.RESOLUTION_MIN); tbMeetingEndDate = new DateField(); tbMeetingEndDate.setResolution(DateField.RESOLUTION_MIN); tbMeetingDuration = new TextField(); //tbMeetingCreatorEmailAddress = new TextField(); //tbMeetingParticipantEmailAddresses = new TextField(); tbMeetingPassword = new PasswordField(); tbConfirmMeetingPassword = new PasswordField(); tbMeetingPassword.setRequired(false); tbConfirmMeetingPassword.setRequired(false); lErrorMessage = new Label("", ContentMode.HTML); VerticalLayout layout = (VerticalLayout)super.InitUI();//Global layout layout.setSpacing(true); layout.setMargin(true); GridLayout gl = new GridLayout(2,6);//Grid layout for text fields gl.setSpacing(true); int row = 0; gl.addComponent(new Label("Meeting Name: "), 0, row); gl.addComponent(tbMeetingName, 1, row++); gl.addComponent(new Label("Meeting Password: "), 0, row); gl.addComponent(tbMeetingPassword, 1, row++); gl.addComponent(new Label("Confirm meeting Password: "), 0, row); gl.addComponent(tbConfirmMeetingPassword, 1, row++); gl.addComponent(new Label("Meeting start date: "), 0, row); gl.addComponent(tbMeetingStartDate, 1, row++); gl.addComponent(new Label("Meeting end date: "), 0, row); gl.addComponent(tbMeetingEndDate, 1, row++); gl.addComponent(new Label("Meeting duration (minutes): "), 0, row); gl.addComponent(tbMeetingDuration, 1, row++); layout.addComponent(gl); tbMeetingStartDate.addValueChangeListener(e -> UpdateStartEndDateLimits()); tbMeetingEndDate.addValueChangeListener(e -> UpdateStartEndDateLimits()); UpdateStartEndDateLimits(); // Join meeting button Button bCreate = new Button("Create meeting"); bCreate.addClickListener(e -> OnCreateMeetingButtonClicked()); layout.addComponent(bCreate); // Error message label layout.addComponent(lErrorMessage); return layout; } private void UpdateStartEndDateLimits() { tbMeetingStartDate.setRangeStart(new Date()); if (tbMeetingStartDate.getValue() != null) tbMeetingEndDate.setRangeStart(tbMeetingStartDate.getValue()); else tbMeetingEndDate.setRangeStart(new Date()); if (tbMeetingEndDate.getValue() != null) tbMeetingStartDate.setRangeEnd(tbMeetingEndDate.getValue()); else tbMeetingStartDate.setRangeEnd(Date.from(Instant.now().plus(365 * 10, ChronoUnit.DAYS)));//screw java date } //Join meeting button click handler. Communicates with DB and changes state according to the return code private void OnCreateMeetingButtonClicked() { // CreateMeeting() takes: // String password, Date startDate, Date endDate, String name, Date duration, long userID // Update text entry fields to reflect same. if(!tbMeetingPassword.getValue().equals(tbConfirmMeetingPassword.getValue())) { setErrorMessage("Passwords must match!"); return; } long duration; try { duration = new Long(tbMeetingDuration.getValue()) * 60; } catch (Exception e) { setErrorMessage("Duration must be a number"); return; } if (duration <= 0) { setErrorMessage("Duration must be a positive number"); return; } if (tbMeetingStartDate.getValue() == null || tbMeetingEndDate.getValidators() == null) { setErrorMessage("Please select start and end dates"); return; } int code = (int) Controllers.DatabaseConnector.CreateMeeting(tbMeetingPassword.getValue(), tbMeetingStartDate.getValue(), tbMeetingEndDate.getValue(), tbMeetingName.getValue(), duration, Controllers.UserID); if (code > 0) { Meeting m = Controllers.DatabaseConnector.GetMeetingDescription(code); UI.getCurrent().getSession().setAttribute("selectedMeeting", m); UI.getCurrent().getNavigator().navigateTo(Constants.URL_MEETING_OVERVIEW); } else { setErrorMessage("Error creating meeting"); System.out.println("Can't create meeting. Error code " + code); return; } } //Display error message in red private void setErrorMessage(String msg) { lErrorMessage.setValue("<font color=\"red\"/>" + msg); } }
package com.mastek.farmToShop.APIs; import javax.ws.rs.BeanParam; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.mastek.farmToShop.entities.AssignedProduct; import com.mastek.farmToShop.entities.Basket; import com.mastek.farmToShop.entities.Customer; @Path("/farmtoshop/") public interface BasketAPI { //http://localhost:7777/farmtoshop/basket/list @GET // http Method: GET to recieve data in requests @Path("/basket/list")// URL path to access this basket List @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) public Iterable<Basket> listAllBaskets(); // http://localhost:7777/farmtoshop/basket/find/ @GET @Path("/basket/find/{basketID}") @Produces({MediaType.APPLICATION_JSON}) public Basket findByBasketid(@PathParam("basketID") int basketID); // http://localhost:7777/farmtoshop/basket/register @POST @Path("/basket/register") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces({MediaType.APPLICATION_JSON}) public Basket registerNewBasket(@BeanParam Basket newBasket); // http://localhost:7777/farmtoshop/basket/delete // @DELETE // @Path("/basket/delete/{basketID}") // @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) // public Basket deleteBasket(@PathParam("basketID") int basketID); /*@DELETE @Path("/basket/product/delete/{basketID}/{produtID}") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces({MediaType.APPLICATION_JSON}) public DeleteProduct removeProductFromBasket(@BeanParam RemoveProduct aProd, @PathParam("basketID") int basketID, @PathParam("productID") int productID); */ }
package us.gibb.dev.gwt.server.jdo; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import us.gibb.dev.gwt.command.Command; import us.gibb.dev.gwt.command.CommandException; import us.gibb.dev.gwt.command.Result; import us.gibb.dev.gwt.server.command.handler.AbstractCommandHandler; import us.gibb.dev.gwt.server.command.handler.Context; public abstract class JDOCommandHandler<C extends Command<R>, R extends Result> extends AbstractCommandHandler<C, R> { private PersistenceManagerFactory pmf; public JDOCommandHandler(PersistenceManagerFactory pmf) { this.pmf = pmf; } @Override public R execute(C command, Context context) throws CommandException { PersistenceManager pm = pmf.getPersistenceManager(); pm.setDetachAllOnCommit(true); try { return execute(pm, command, context); } finally { pm.close(); } } protected abstract R execute(PersistenceManager pm, C command, Context context); }
package com.keybellsoft.parseexample; /** * Copyright (C) 2015 KeyBellSoft. All rights reserved. * Created by Fabian Rosales on 25/10/2015. * www.frosquivel.com * * * Use for example * https://github.com/rey5137/material * www.parse.com */ import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent(MainActivity.this, LoginActivity.class); startActivity(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return true; } }
package servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.ClassInfoBean; import dao.ClassInfoDao; public class ClassInfoServlet extends HttpServlet{ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //设置编码,防止请求乱码 req.setCharacterEncoding("UTF-8"); //获取参数 String className=req.getParameter("className"); String classId=req.getParameter("classId"); //System.out.println(classId); //创建ClassInfoBean对象保存信息 ClassInfoBean bean =new ClassInfoBean(); bean.setCname(className); bean.setCid(Integer.valueOf(classId)); System.out.println(bean.getCid()); //创建数据库操作对象 ClassInfoDao dao =new ClassInfoDao(); //新增班级信息到数据库 dao.addClassInfo(bean); //查询所有班级信息 List<ClassInfoBean> classInfo=dao.findAll(); //保存查询的班级信息 req.setAttribute("classInfo", classInfo); //转发请求 req.getRequestDispatcher("/classInfo.jsp").forward(req, resp); } }
package com.app.web; import com.app.model.Message; import com.app.service.MessagesService; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static spark.Spark.*; @RequiredArgsConstructor @Slf4j public class Routing { private final MessagesService messagesService; public void initRoutes() { Gson gson = new GsonBuilder().setPrettyPrinting().create(); options("/*", (request, response) -> "PREFLIGHT REQUEST DONE"); after((request, response) -> { response.header("Access-Control-Allow-Origin", "http://localhost:3000"); response.header("Access-Control-Allow-Headers", "Content-Type,Authorization"); response.header("Access-Control-Allow-Methods", "*"); }); path("/messages", () -> { get("", (request, response) -> { var messages = messagesService.findAll(); response.status(200); response.header("Content-Type", "application/json;charset=utf-8"); return messages; }, new JsonTransformer()); post("", (request, response) -> { log.info("Authorization: {}", request.headers("Authorization")); var message = gson.fromJson(request.body(), Message.class); response.status(201); response.header("Content-Type", "application/json;charset=utf-8"); return messagesService.add(message); }, new JsonTransformer()); }); } }
package net.oneqas.fileEnviron.fileService; import org.springframework.stereotype.Component; @Component public class GroupAggregateImgFileServiceImpl extends FileServiceImpl { static { PATH = "server/imgs/groupImages/"; } }
package com.yuan.library.bannerdialog; import android.app.Activity; import android.content.Context; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Toast; import androidx.annotation.NonNull; import com.bumptech.glide.Glide; import com.yuan.library.R; import java.util.List; /** * yuan * 2020/2/22 **/ public class BannerDialog{ private ViewGroup decorView; private BannerDialogView bannerDialogView; private BannerDialog(@NonNull Activity context, Builder builder) { super(); decorView = context.getWindow().getDecorView().findViewById(android.R.id.content); bannerDialogView = new BannerDialogView(context, builder); decorView.addView(bannerDialogView); } public static class Builder { private Activity context; private List<String> imageList; private int selectColor; private int normalColor; private OnImageClickListener onImageClickListener; public Builder(@NonNull final Activity context) { super(); this.context = context; selectColor = context.getResources().getColor(R.color.selectColor); normalColor = context.getResources().getColor(R.color.normalColor); onImageClickListener = new OnImageClickListener() { @Override public void onImageClick(int index) { Toast.makeText(context, "" + index, Toast.LENGTH_SHORT).show(); } }; } public Builder imageList(List<String> imageList) { this.imageList = imageList; return this; } public Builder selectColor(int selectColor) { this.selectColor = selectColor; return this; } public Builder normalColor(int normalColor) { this.normalColor = normalColor; return this; } List<String> getImageList() { return imageList; } int getSelectColor() { return selectColor; } int getNormalColor() { return normalColor; } LoadImageToView getLoadImageToView() { return new LoadImageToView() { @Override public void loadImageToView(ImageView imageView, String url) { Glide.with(context).load(url).into(imageView); } }; } public Builder onImageClickListener(OnImageClickListener onImageClickListener) { this.onImageClickListener = onImageClickListener; return this; } Context getContext() { return context; } OnImageClickListener getOnImageClickListener() { return onImageClickListener; } public void build() { new BannerDialog(context, this); } } }
package net.sourceforge.jFuzzyLogic.membership.functions; import net.sourceforge.jFuzzyLogic.rule.FuzzyRuleSet; /** * Membership function that is a (simple) mathematical funcion * Function: cos(x1) * * @author pcingola@users.sourceforge.net */ public class MffCos extends MffFunction { /** Constructor */ public MffCos(FuzzyRuleSet fuzzyRuleSet, Object terms[]) { super(fuzzyRuleSet, terms); } @Override protected double evaluateFunction() { if( values.length != 1 ) throw new RuntimeException("Function Exp needs only one argument: cos(x)"); return Math.cos(values[0]); } @Override public String toString() { if( terms == null ) return ""; return "cos( " + terms[0].toString() + " )"; } }
/** * */ package com.fixit.core.dao.sql; import java.io.Serializable; import java.util.Map; import com.fixit.core.dao.CommonDao; import com.fixit.core.data.sql.SqlModelObject; /** * @author Kostyantin * @createdAt 2016/12/15 21:49:05 GMT+2 */ public interface SqlDao<E extends SqlModelObject<ID>, ID extends Serializable> extends CommonDao<E, ID>, HibernateDao { Long getCount(Map<String, Object> properties); boolean contains(E entity); }
package com.logicbig.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Profile; import java.math.BigDecimal; @SpringBootConfiguration public class ExampleMain { @Bean @Profile("in-memory") InventoryService inMemoryInventoryService() { return new InMemoryInventoryServiceImpl(); } @Bean @Profile("production") InventoryService productionInventoryService() { return new InventoryServiceImpl(); } public static void main(String[] args) throws InterruptedException { ApplicationContext context = SpringApplication.run(ExampleMain.class, args); InventoryService service = context.getBean(InventoryService.class); service.addStockItem("item1", 10, BigDecimal.valueOf(20.5)); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Model; /** * * @author HermanCosta */ public class Sale extends Customer { String saleNo, stringProducts, stringQty, stringUnitPrice, stringPriceTotal, saleDate, status, createdBy; double total, cash, card, changeTotal; public Sale(String _saleNo, String _firstName, String _lastName, String _contactNo, String _email, String _stringProducts, String _stringQty, String _stringUnitPrice, String _stringPriceTotal, double _total, String _saleDate, double _cash, double _card, double _changeTotal, String _status, String _createdBy) { super(_firstName, _lastName, _contactNo, _email); this.saleNo = _saleNo; this.stringProducts = _stringProducts; this.stringQty = _stringQty; this.stringUnitPrice = _stringUnitPrice; this.stringPriceTotal = _stringPriceTotal; this.total = _total; this.saleDate = _saleDate; this.cash = _cash; this.card = _card; this.changeTotal = _changeTotal; this.status = _status; this.createdBy = _createdBy; } public String getSaleNo() { return saleNo; } public void setSaleNo(String sellingNo) { this.saleNo = sellingNo; } public String getStringProducts() { return stringProducts; } public void setStringProducts(String stringProducts) { this.stringProducts = stringProducts; } public String getStringQty() { return stringQty; } public void setStringQty(String stringQty) { this.stringQty = stringQty; } public String getStringUnitPrice() { return stringUnitPrice; } public void setStringUnitPrice(String stringUnitPrice) { this.stringUnitPrice = stringUnitPrice; } public String getStringPriceTotal() { return stringPriceTotal; } public void setStringPriceTotal(String stringPriceTotal) { this.stringPriceTotal = stringPriceTotal; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } public String getSaleDate() { return saleDate; } public void setSaleDate(String sellingDate) { this.saleDate = sellingDate; } public double getCash() { return cash; } public void setCash(double cash) { this.cash = cash; } public double getCard() { return card; } public void setCard(double card) { this.card = card; } public double getChangeTotal() { return changeTotal; } public void setChangeTotal(double changeTotal) { this.changeTotal = changeTotal; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getUsername() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } }
package client; import client.commen.MapperUtils; import client.commen.SwingUtils; import mp.dao.PrimaryMapper; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddressList; import org.apache.poi.ss.util.NumberToTextConverter; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import static org.apache.poi.ss.usermodel.CellType.BLANK; /** * @description: 界面展示 * @author: liyue * @date: 2020/11/23 11:46 */ public class ClientComponent { static String FILL_PATH ="C:\\Users\\41204\\Desktop\\DBE.xls"; public static void placeComponents(JPanel panel) { /* 布局部分我们这边不多做介绍 * 这边设置布局为 null */ panel.setLayout(null); // 创建上传按钮 JButton uploudButton = SwingUtils.buildJButton("上传Excle",90, 10, 125, 45); addActionListener2(uploudButton); panel.add(uploudButton); // 创建下载按钮 JButton downlouButton = SwingUtils.buildJButton("下载模板",90, 50, 125, 45); addActionListener1(downlouButton); panel.add(downlouButton); // 创建设置按钮 JButton DBsetButton = SwingUtils.buildJButton("数据库设置",90, 90, 125, 45); addActionListener(DBsetButton); panel.add(DBsetButton); } /** * 下载模板按钮事件 * @param saveButton */ private static void addActionListener1(JButton saveButton) { // 为按钮绑定监听器 saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { { // 创建一个excel对象 HSSFWorkbook wb = null; String excelName = "DBE模板"; wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(excelName); HSSFRow row = sheet.createRow(0); row.setHeightInPoints(20); CellRangeAddressList regions = new CellRangeAddressList(0, 0, 0, 0); //获取单元格的坐标 sheet.setDefaultColumnWidth(500); OutputStream output; try { output = new FileOutputStream(FILL_PATH); wb.write(output); output.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } } }); } /** * 上传模板按钮事件 * @param saveButton */ private static void addActionListener2(JButton saveButton) { // 为按钮绑定监听器 saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { { MultipartFile file = null; try{ File file1 = new File(FILL_PATH); //将File格式转换为MultipartFile格式 FileInputStream fileInputStream = new FileInputStream(file1); file = new MockMultipartFile(file1.getName(), fileInputStream); }catch (Exception ex){ ex.printStackTrace(); } //判断文件是否是excel文件 if(!file.getOriginalFilename().endsWith("xls") && !file.getOriginalFilename().endsWith("xlsx")){ // 不是excel文件 } // 获取SQL集合 List<String> sqlList = getDataFromExcel(file); // 数据库执行SQL List<List<Map<String, Object>>> rsList = getRSForDB(sqlList); // 将返回值序列化为Ecsle exportEcsle(rsList); } } private void exportEcsle(List<List<Map<String, Object>>> rsList) { if(rsList == null || rsList.size()==0) return; } @Autowired MapperUtils mapperUtils; private List<List<Map<String, Object>>> getRSForDB(List<String> sqlList) { List<List<Map<String, Object>>> rslist = new ArrayList<>(); for (String sql :sqlList ) { List<Map<String,Object>> rs = mapperUtils.getList(sql); if(rs != null && rs.size()>0) rslist.add(rs); } return rslist; } }); } public static List<String> getDataFromExcel(MultipartFile file) { //获得Workbook工作薄对象 Workbook workbook = getWorkBook(file); //创建返回对象,把每行中的值作为一个ExcelParamVo,所有行作为一个集合返回 List<String> list = new ArrayList<String>(); if(workbook != null){ for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){ //获得当前sheet工作表 Sheet sheet = workbook.getSheetAt(sheetNum); if(sheet == null){ continue; } //获得当前sheet的开始行 int firstRowNum = sheet.getFirstRowNum(); //获得当前sheet的结束行 int lastRowNum = sheet.getLastRowNum(); //循环除了第一行的所有行 for(int rowNum = firstRowNum;rowNum <= lastRowNum;rowNum++){ //获得当前行 Row row = sheet.getRow(rowNum); if(isRowEmpty(row)){ continue; } //获得当前行的开始列 int firstCellNum = row.getFirstCellNum(); //获得当前行的列数 int lastCellNum = row.getLastCellNum(); String[] cells = new String[row.getLastCellNum()]; String sql = null; //循环当前列 for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){ if(cellNum == 0){ Cell cell = row.getCell(cellNum); sql = getCellValue(cell); } } list.add(sql); } } } return list; } /** * 数据库设置按钮事件 * @param saveButton */ private static void addActionListener(JButton saveButton) { // 为按钮绑定监听器 saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 对话框 //JOptionPane.showMessageDialog(null, "保存成功!"); // 创建 JFrame 实例 JFrame frame = new JFrame("DBEClient"); // Setting the width and height of frame frame.setSize(700, 220); /** * 下边的这句话,如果这么写的话,窗口关闭,springboot项目就会关掉,使用 * dispose则不会 */ frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //frame.dispose(); //如果写这句可实现窗口关闭,springboot项目仍运行 /* 创建面板,这个类似于 HTML 的 div 标签 * 我们可以创建多个面板并在 JFrame 中指定位置 * 面板中我们可以添加文本字段,按钮及其他组件。 */ JPanel panel = new JPanel(); // 添加面板 frame.add(panel); /* * 调用用户定义的方法并添加组件到面板 */ new DBsetForm().placeComponents(panel); // 设置界面可见 frame.setVisible(true); } }); } public static Workbook getWorkBook(MultipartFile file) { //获得文件名 String fileName = file.getName(); //创建Workbook工作薄对象,表示整个excel Workbook workbook = null; try { //获取excel文件的io流 InputStream is = file.getInputStream(); //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象 if(fileName.endsWith("xls")){ //2003 workbook = new HSSFWorkbook(is); }else if(fileName.endsWith("xlsx")){ //2007 及2007以上 SXSSFWorkbook workBooke = new SXSSFWorkbook(new XSSFWorkbook(is),-1); workbook = workBooke.getXSSFWorkbook(); } } catch (IOException e) { System.out.println(e.getMessage()); } return workbook; } public static boolean isRowEmpty(Row row) { for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) { Cell cell = row.getCell(c); if (cell != null && cell.getCellType() != BLANK) return false; } return true; } /** * 时间格式处理 * @return * @data 2017年11月27日 */ public static String stringDateProcess(Cell cell){ String result = new String(); if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式 SimpleDateFormat sdf = null; if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) { sdf = new SimpleDateFormat("HH:mm"); } else {// 日期 sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); } Date date = cell.getDateCellValue(); result = sdf.format(date); } else if (cell.getCellStyle().getDataFormat() == 58) { // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); double value = cell.getNumericCellValue(); Date date = org.apache.poi.ss.usermodel.DateUtil .getJavaDate(value); result = sdf.format(date); } else { double value = cell.getNumericCellValue(); CellStyle style = cell.getCellStyle(); DecimalFormat format = new DecimalFormat(); String temp = style.getDataFormatString(); // 单元格设置成常规 if (temp.equals("General")) { format.applyPattern("#"); } result = format.format(value); } return result; } public static String getCellValue(Cell cell){ String cellvalue = ""; if (cell != null) { // 判断当前Cell的Type switch (cell.getCellType()) { // 如果当前Cell的Type为NUMERIC case NUMERIC : { short format = cell.getCellStyle().getDataFormat(); if(format == 14 || format == 31 || format == 57 || format == 58){ //excel中的时间格式 cellvalue= stringDateProcess(cell); } // 判断当前的cell是否为Date else if (HSSFDateUtil.isCellDateFormatted(cell)) { //先注释日期类型的转换,在实际测试中发现HSSFDateUtil.isCellDateFormatted(cell)只识别2014/02/02这种格式。 cellvalue= stringDateProcess(cell); } else { // 如果是纯数字 // 取得当前Cell的数值 cellvalue = NumberToTextConverter.toText(cell.getNumericCellValue()); } break; } // 如果当前Cell的Type为STRIN case STRING: // 取得当前的Cell字符串 cellvalue = cell.getStringCellValue().replaceAll("'", "''"); break; case BLANK: cellvalue = null; break; // 默认的Cell值 case BOOLEAN: // Boolean cellvalue = cell.getBooleanCellValue() + ""; break; case FORMULA: // 公式 cellvalue = cell.getCellFormula() + ""; break; case ERROR: cellvalue = cell.getErrorCellValue() + ""; break; default:{ cellvalue = " "; } } } else { cellvalue = ""; } return cellvalue; } }
package peropt.me.com.performaceoptimization.dn; /** * desc: */ public class Looper { MessageQueue mMessageQueue; private Looper() { mMessageQueue = new MessageQueue(); } }
package com.theshoes.jsp.cs.model.dao; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.theshoes.jsp.common.paging.SelectCriteria; import com.theshoes.jsp.cs.model.dto.QuestionDTO; import com.theshoes.jsp.cs.model.dto.QuestionFileDTO; import com.theshoes.jsp.cs.model.dto.RequestDTO; public class QuestionDAO { /* 문의글 삽입 */ public int insertQuestion(SqlSession session, QuestionDTO question) { System.out.println("qdao:"+question); return session.insert("QuestionDAO.insertQuestion", question); } /* 문의글 썸네일 삽입 */ public int insertQuestionFile(SqlSession session, QuestionFileDTO questionThumbDTO) { System.out.println("dao" + questionThumbDTO); return session.insert("QuestionDAO.insertQuestionFile", questionThumbDTO); } /* 전체 문의글 수 조회 */ public int selectCsTotalCount(SqlSession session) { return session.selectOne("QuestionDAO.selectCsTotalCount"); } /* 전체 문의글 목록 조회 */ public List<QuestionDTO> selectAllCsList(SqlSession session, SelectCriteria selectCriteria) { System.out.println("questionDAO : " + selectCriteria); return session.selectList("QuestionDAO.selectAllCsList", selectCriteria); } /* 사진 있는 문의글 상세보기 */ public QuestionDTO selectCsDetail(SqlSession session, int csNo) { System.out.println("~ DAO 문의글 상세보기 : " + csNo); QuestionDTO test = session.selectOne("QuestionDAO.selectCsDetail", csNo); System.out.println("test : " + test); return test; } /* 사진 없는 문의글 상세보기 */ public QuestionDTO selectCsDetailNoPhoto(SqlSession session, int csNo) { System.out.println("사진 없는 문의글 상세보기 dao"); return session.selectOne("QuestionDAO.selectCsDetailNoPhoto", csNo); } /* 답변글 등록하기 */ public int registRequest(SqlSession session, RequestDTO requestDTO) { System.out.println("dao 답변글 등록 완료 : " + requestDTO); return session.insert("QuestionDAO.registRequest", requestDTO); } /* 답변글 개수 확인 */ public int selectRequestCount(SqlSession session) { System.out.println("DAO 답변글 갯수 "); return session.selectOne("QuestionDAO.selectRequestCount"); } /* 답변글 상세보기 */ public RequestDTO selectRequestDetail(SqlSession session, int csNo) { System.out.println("랄랄라 dao 답변글 상세보기 : " + csNo); return session.selectOne("QuestionDAO.selectRequestDetail", csNo); } }
package com.example.demo.service.impl; import com.example.demo.dto.common.BaseRequest; import com.example.demo.dto.common.BaseResponse; import com.example.demo.dto.common.Result; import com.example.demo.service.RpcManager; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Service; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @author songjuxing */ @Service("rpcManager") public class RpcManagerImpl implements ApplicationContextAware, RpcManager { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public Result<? extends BaseResponse> invoke(String rpcName, String rpcMethod, BaseRequest request) { Result<? extends BaseResponse> res = null; try { Object bean = applicationContext.getBean(rpcName); Method method = bean.getClass().getMethod(rpcMethod, BaseRequest.class); res = (Result<? extends BaseResponse>)method.invoke(bean, request); } catch (Exception e) { e.printStackTrace(); } return res; } }
package com.vicutu.batchdownload.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.vicutu.batchdownload.dao.DownloadDetailDao; import com.vicutu.batchdownload.domain.DownloadDetail; import com.vicutu.batchdownload.service.DownloadDetailService; @Service public class DownloadDetailServiceImpl implements DownloadDetailService { private DownloadDetailDao downloadDetailDao; @Autowired public void setDownloadDetailDao(DownloadDetailDao downloadDetailDao) { this.downloadDetailDao = downloadDetailDao; } @Override public void saveOrUpdateDownloadDetail(DownloadDetail downloadDetail) { downloadDetailDao.saveOrUpdateAccessDetail(downloadDetail); } }
package com.trannguyentanthuan2903.yourfoods.favorites.model; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; 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.squareup.picasso.Picasso; import com.trannguyentanthuan2903.yourfoods.R; import com.trannguyentanthuan2903.yourfoods.comment.view.CommentActivity; import com.trannguyentanthuan2903.yourfoods.favorites.FavoriteFragment; import com.trannguyentanthuan2903.yourfoods.main.view.MainUser2Activity; import com.trannguyentanthuan2903.yourfoods.main.view.MainUserActivity; import com.trannguyentanthuan2903.yourfoods.profile_store.model.Store; import com.trannguyentanthuan2903.yourfoods.store_list.presenter.StoreListPresenter; import com.trannguyentanthuan2903.yourfoods.utility.Constain; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; /** * Created by Administrator on 10/31/2017. */ public class FavoriteAdapter extends RecyclerView.Adapter<FavoriteViewHolder> { private ArrayList<Store> arrStore; private String sumShipped; private long sumFavorite; private long sumComment; private String idStore; private String idUser; private String emailUser; private String emailStore; private Context mContext; private DatabaseReference mData; private String linkPhotoStore, timeWork = ""; private FavoriteFragment favoriteFragment; private boolean flagVisibility = false; private StoreListPresenter presenter; private double loUser = 0, laUser = 0, loStore = 0, laStore = 0, distance; public FavoriteAdapter(ArrayList<Store> arrStore, FavoriteFragment favorite_fragment, String idUser, Context mContext) { this.arrStore = arrStore; this.favoriteFragment = favorite_fragment; this.idUser = idUser; this.mContext = mContext; presenter = new StoreListPresenter(); mData = FirebaseDatabase.getInstance().getReference(); } @Override public FavoriteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_store, parent,false); return new FavoriteViewHolder(itemView); } @Override public void onBindViewHolder(final FavoriteViewHolder holder, final int position) { final Store store = arrStore.get(position); idStore = store.getIdStore(); sumShipped = String.valueOf(store.getSumShipped()); holder.txtStoreName.setText(store.getStoreName()); holder.txtSumShipped.setText("Đã giao thành công " + sumShipped + " lần"); holder.txtSumProduct.setText("Tổng cộng " + store.getSumProduct() + " sản phẩm"); if (store.getIsOpen() == 0) { holder.txtStatus.setText("Mở cửa"); } else if (store.getIsOpen() == 1) { holder.txtStatus.setText("Đóng cửa"); } //get LinkPhotoStore and Opent with Glide linkPhotoStore = store.getLinkPhotoStore(); if (!linkPhotoStore.equals("")) { /*Glide.with(store_list_fragment.getActivity()) .load(linkPhotoStore) .preload(225, 225) .into(holder.imgPhotoStore);*/ Picasso.with(mContext) .load(linkPhotoStore) .resize(225, 225) .centerCrop() .placeholder(R.drawable.store) .error(R.drawable.store) .into(holder.imgPhotoStore); } try { //get Address Store mData.child(Constain.STORES).child(idStore).child(Constain.LOCATION).child(Constain.ADDRESS).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { holder.txtAddress.setText(dataSnapshot.getValue().toString()); } @Override public void onCancelled(DatabaseError databaseError) { } }); } catch (Exception ex) { ex.printStackTrace(); } try { //get Timework mData.child(Constain.STORES).child(idStore).child(Constain.TIME_WORK).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { timeWork = dataSnapshot.getValue().toString(); holder.txtTimeWork.setText(timeWork); } @Override public void onCancelled(DatabaseError databaseError) { } }); } catch (Exception ex) { ex.printStackTrace(); } try { //get Email mData.child(Constain.STORES).child(idStore).child(Constain.EMAIL).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { emailStore = dataSnapshot.getValue().toString(); holder.txtEmailStore.setText(emailStore); } @Override public void onCancelled(DatabaseError databaseError) { } }); } catch (Exception ex) { ex.printStackTrace(); } try { //get sumFavorite mData.child(Constain.STORES).child(idStore).child(Constain.FAVORITE_LIST).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null) { sumFavorite = dataSnapshot.getChildrenCount(); holder.txtSumfavorite.setText(String.valueOf(sumFavorite)); for (DataSnapshot dt : dataSnapshot.getChildren()) { if (idUser.equals(dt.getKey().toString())) { holder.imgHeart.setImageResource(R.drawable.heart); } } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } catch (Exception ex) { ex.printStackTrace(); } try { //get Lo and la User mData.child(Constain.USERS).child(idUser).child(Constain.LOCATION).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null) { try { HashMap<String, Object> location = new HashMap<String, Object>(); location = (HashMap<String, Object>) dataSnapshot.getValue(); loUser = (double) location.get(Constain.LO); laUser = (double) location.get(Constain.LA); } catch (Exception ex) { ex.printStackTrace(); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } catch( Exception ex) { ex.printStackTrace(); } try { //get Longtitude and Latitude store and Caculator Distance mData.child(Constain.STORES).child(idStore).child(Constain.LOCATION).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null) { try { HashMap<String, Object> location = new HashMap<>(); location = (HashMap<String, Object>) dataSnapshot.getValue(); loStore = (double) location.get(Constain.LO); laStore = (double) location.get(Constain.LA); if (loUser != 0 && laUser != 0 && loStore != 0 && laStore != 0) { distance = calculationByDistance(laUser, loUser, laStore, loStore); distance = Math.round(distance); holder.txtDistance.setText(String.valueOf(distance) + " Km"); } } catch (Exception ex) { ex.printStackTrace(); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } catch( Exception ex) { ex.printStackTrace(); } //set Item click holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v){ if (flagVisibility == true) { holder.linearLayout.setVisibility(View.VISIBLE); flagVisibility = false; } else { holder.linearLayout.setVisibility(View.GONE); flagVisibility = true; } } }); //imgHeart Click holder.imgHeart.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v){ try { Store store1 = arrStore.get(position); final String idStore1 = store1.getIdStore(); mData.child(Constain.STORES).child(idStore1).child(Constain.FAVORITE_LIST).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null) { boolean flag = true; for (DataSnapshot dt : dataSnapshot.getChildren()) { if (idUser.equals(dt.getKey())) { flag = false; } } if (!flag) { //remove and change img sumFavorite = dataSnapshot.getChildrenCount() - 1; holder.txtSumfavorite.setText(String.valueOf(sumFavorite)); holder.imgHeart.setImageResource(R.drawable.non_heart); presenter.removeHeart(idStore1, idUser); } else { //add and change img holder.imgHeart.setImageResource(R.drawable.heart); sumFavorite = dataSnapshot.getChildrenCount() + 1; holder.txtSumfavorite.setText(String.valueOf(sumFavorite)); presenter.addHeart(idStore1, idUser, emailUser); } } else { holder.imgHeart.setImageResource(R.drawable.heart); holder.txtSumfavorite.setText("1"); presenter.addHeart(idStore1, idUser, emailUser); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } catch (Exception ex) { } } }); // txtHeart Click holder.txtSumfavorite.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v){ try { Store store1 = arrStore.get(position); final String idStore1 = store1.getIdStore(); mData.child(Constain.STORES).child(idStore1).child(Constain.FAVORITE_LIST).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null) { boolean flag = true; for (DataSnapshot dt : dataSnapshot.getChildren()) { if (idUser.equals(dt.getKey())) { flag = false; } } if (!flag) { //remove and change img sumFavorite = dataSnapshot.getChildrenCount() - 1; holder.txtSumfavorite.setText(String.valueOf(sumFavorite)); holder.imgHeart.setImageResource(R.drawable.non_heart); presenter.removeHeart(idStore1, idUser); } else { //add and change img holder.imgHeart.setImageResource(R.drawable.heart); sumFavorite = dataSnapshot.getChildrenCount() + 1; holder.txtSumfavorite.setText(String.valueOf(sumFavorite)); presenter.addHeart(idStore1, idUser, emailUser); } } else { holder.imgHeart.setImageResource(R.drawable.heart); holder.txtSumfavorite.setText("1"); presenter.addHeart(idStore1, idUser, emailUser); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } catch (Exception ex) { } } }); //btn Callnow click holder.btnViewProfileStore.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v){ Store store1 = arrStore.get(position); ((MainUserActivity) mContext).moveToProfileStoreFragment(store1.getIdStore()); } }); //btnView Order click holder.btnViewOrder.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v){ Store store2 = arrStore.get(position); Intent intent = new Intent(mContext, MainUser2Activity.class); intent.putExtra(Constain.ID_STORE, store2.getIdStore()); intent.putExtra(Constain.ID_USER, idUser); intent.putExtra(Constain.IS_STORE, false); mContext.startActivity(intent); } }); holder.imgComment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent cmtIntent = new Intent(mContext, CommentActivity.class); cmtIntent.putExtra("id_store",store.getIdStore()); mContext.startActivity(cmtIntent); } }); //sum comment try { //get sumComment mData.child(Constain.STORES).child(idStore).child(Constain.COMMENTS).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null) { sumComment = dataSnapshot.getChildrenCount(); holder.txtSumComment.setText(String.valueOf(sumComment)); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } catch (Exception ex) { ex.printStackTrace(); } } @Override public int getItemCount() { return arrStore.size(); } //set UserName public void setEmailUser(String emailUser) { this.emailUser = emailUser; } //Caculator Distance public final double calculationByDistance(double lat1, double lon1, double lat2, double lon2) { int Radius = 6371;// radius of earth in Km double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); double c = 2 * Math.asin(Math.sqrt(a)); double valueResult = Radius * c; double km = valueResult / 1; DecimalFormat newFormat = new DecimalFormat("####"); int kmInDec = Integer.valueOf(newFormat.format(km)); double meter = valueResult % 1000; int meterInDec = Integer.valueOf(newFormat.format(meter)); Log.i("Radius Value", "" + valueResult + " KM " + kmInDec + " Meter " + meterInDec); return Radius * c; } }
package labs.chapter6; public class Lab { public static void main (String[] args) { // int i = 0; // while (i < 10) // { // System.out.println("Number is " + i); // System.out.println("Square is " + (i * i)); // if (i % 2 != 0) // { // System.out.println("Cube is " + (i * i * i)); // } // i++; // } // own solution // int[] numbers = new int[20]; // for (int j = 0; j < 20; j++) // { // for (int i = 2; i < 20; i++) // { // numbers[0] = 0; // numbers[1] = 1; // numbers[i] = numbers[i-2] + numbers[i-1]; // } // System.out.println(j + ": " + numbers[j]); // } // course solution int f0 = 0; int f1 = 1; System.out.println("0: " + f0); System.out.println("1: " + f1); for (int i = 2; i < 20; i++) { int sum = f0 + f1; System.out.println(i + ": " + sum); f0 = f1; f1 = sum; } } }
package com.company; import ru.ifmo.se.pokemon.*; public class Tickle extends SpecialMove { protected void applyOppEffects(Pokemon p) { p.addEffect(new Effect().stat(Stat.DEFENSE, 1)); p.addEffect(new Effect().stat(Stat.ATTACK, 1)); } @Override protected String describe() { return "Tickle"; } }
package view; import java.awt.EventQueue; import javax.swing.JInternalFrame; import javax.swing.JPanel; import javax.swing.border.TitledBorder; import Dao.CostumeDao; import bean.CostumeInfo; import util.DbUtil; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import javax.swing.JTextField; import javax.swing.JComboBox; import javax.swing.JCheckBox; import javax.swing.JButton; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.SQLException; import java.awt.event.ActionEvent; public class ColorAndSizeInterFrame extends JInternalFrame { private JTextField id1; private JTextField color1; private JTextField id2; private JTextField color2; private JCheckBox vsmall1; private JCheckBox small1; private JCheckBox mediem1; private JCheckBox large1; private JCheckBox vlarge1; private CostumeDao costumeDao = new CostumeDao(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ColorAndSizeInterFrame frame = new ColorAndSizeInterFrame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ColorAndSizeInterFrame() { setIconifiable(true); setClosable(true); setTitle("服装颜色和尺码管理"); setBounds(100, 100, 563, 337); getContentPane().setLayout(null); JPanel panel = new JPanel(); panel.setBorder(new TitledBorder(null, "添加服装颜色和尺码", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel.setBounds(24, 21, 253, 266); getContentPane().add(panel); panel.setLayout(null); JLabel l1 = new JLabel("服装编号:"); l1.setFont(new Font("黑体", Font.PLAIN, 14)); l1.setBounds(24, 29, 72, 26); panel.add(l1); id1 = new JTextField(); id1.setFont(new Font("黑体", Font.PLAIN, 14)); id1.setBounds(100, 31, 109, 24); panel.add(id1); id1.setColumns(10); JLabel l2 = new JLabel("添加的颜色:"); l2.setFont(new Font("黑体", Font.PLAIN, 14)); l2.setBounds(24, 88, 86, 26); panel.add(l2); color1 = new JTextField(); color1.setFont(new Font("黑体", Font.PLAIN, 14)); color1.setColumns(10); color1.setBounds(107, 89, 102, 24); panel.add(color1); JLabel l3 = new JLabel("添加的尺码:"); l3.setFont(new Font("黑体", Font.PLAIN, 14)); l3.setBounds(24, 157, 86, 26); panel.add(l3); vsmall1 = new JCheckBox("超小号"); vsmall1.setFont(new Font("黑体", Font.PLAIN, 12)); vsmall1.setBounds(120, 134, 61, 23); panel.add(vsmall1); small1 = new JCheckBox("小号"); small1.setFont(new Font("黑体", Font.PLAIN, 12)); small1.setBounds(183, 134, 49, 23); panel.add(small1); mediem1 = new JCheckBox("中号"); mediem1.setFont(new Font("黑体", Font.PLAIN, 12)); mediem1.setBounds(120, 159, 49, 23); panel.add(mediem1); large1 = new JCheckBox("大号"); large1.setFont(new Font("黑体", Font.PLAIN, 12)); large1.setBounds(183, 159, 49, 23); panel.add(large1); vlarge1 = new JCheckBox("超大号"); vlarge1.setFont(new Font("黑体", Font.PLAIN, 12)); vlarge1.setBounds(120, 186, 61, 23); panel.add(vlarge1); JButton addBtn = new JButton("添加"); addBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addActionPerformed(e); } }); addBtn.setFont(new Font("黑体", Font.PLAIN, 14)); addBtn.setBounds(81, 218, 97, 33); panel.add(addBtn); JPanel panel_1 = new JPanel(); panel_1.setBorder(new TitledBorder(null, "删除服装颜色和尺码", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panel_1.setBounds(287, 21, 245, 266); getContentPane().add(panel_1); panel_1.setLayout(null); JLabel l4 = new JLabel("服装编号:"); l4.setFont(new Font("黑体", Font.PLAIN, 14)); l4.setBounds(24, 30, 72, 26); panel_1.add(l4); id2 = new JTextField(); id2.setFont(new Font("黑体", Font.PLAIN, 14)); id2.setColumns(10); id2.setBounds(100, 32, 109, 24); panel_1.add(id2); JLabel l5 = new JLabel("删除的颜色:"); l5.setFont(new Font("黑体", Font.PLAIN, 14)); l5.setBounds(24, 89, 86, 26); panel_1.add(l5); color2 = new JTextField(); color2.setFont(new Font("黑体", Font.PLAIN, 14)); color2.setColumns(10); color2.setBounds(107, 90, 102, 24); panel_1.add(color2); JButton deleteBtn = new JButton("删除"); deleteBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { deleteActionPerformed(e); } }); deleteBtn.setFont(new Font("黑体", Font.PLAIN, 14)); deleteBtn.setBounds(74, 219, 97, 33); panel_1.add(deleteBtn); } private void deleteActionPerformed(ActionEvent evt) { // TODO Auto-generated method stub if (id2.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "请输入服装编号!"); return; } int costumeId = Integer.parseInt(id2.getText()); String color = color2.getText(); if (color.isEmpty()) { JOptionPane.showMessageDialog(null, "颜色不能为空!"); return; } Connection conn = null; try { conn = DbUtil.getConnection(); int amount = costumeDao.deleteInfos(conn, costumeId, color); if (amount > 0) { JOptionPane.showMessageDialog(null, "成功删除"+amount+"条信息!"); dispose(); }else { JOptionPane.showMessageDialog(null, "删除失败!"); } } catch (Exception e) { // TODO Auto-generated catch block JOptionPane.showMessageDialog(null, "删除失败!"); e.printStackTrace(); }finally { DbUtil.close(conn); } } private void addActionPerformed(ActionEvent evt) { // TODO Auto-generated method stub if (id1.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "请输入服装编号!"); return; } int costumeId = Integer.parseInt(id1.getText()); int count = 0; String color = color1.getText(); if (color.isEmpty()) { JOptionPane.showMessageDialog(null, "颜色不能为空!"); return; } String[] sizes = new String[5]; if (vsmall1.isSelected()) { sizes[0]="超小号"; count++; } if (small1.isSelected()) { sizes[1]="小号"; count++; } if (mediem1.isSelected()) { sizes[2]="中号"; count++; } if (large1.isSelected()) { sizes[3]="大号"; count++; } if (vlarge1.isSelected()) { sizes[4]="超大号"; count++; } CostumeInfo[] costumeInfos = new CostumeInfo[count]; for (int i = 0,k = 0;i < count;i++) { costumeInfos[i] = new CostumeInfo(); // 必须要这一步,不然NullPointerException costumeInfos[i].setCostumeId(costumeId); costumeInfos[i].setColor(color); while (sizes[k]==null) { k++; } costumeInfos[i].setSize(sizes[k++]); } Connection conn = null; try { conn = DbUtil.getConnection(); boolean isExsist = costumeDao.isExist(conn, costumeId); if (!isExsist) { JOptionPane.showMessageDialog(null, "该服装不存在,无法添加颜色和尺码!"); return; } int amount = costumeDao.addInfos(conn, costumeInfos); if (amount > 0) { JOptionPane.showMessageDialog(null, "成功添加"+amount+"条服装颜色和尺码信息!"); dispose(); }else { JOptionPane.showMessageDialog(null, "添加失败!"); } } catch (Exception e) { // TODO Auto-generated catch block JOptionPane.showMessageDialog(null, "添加失败!"); e.printStackTrace(); }finally { DbUtil.close(conn); } } }
package Decorate; /** * Date: 2019/3/2 * Created by Liuian */ class Decorate1 extends BaseDecorate { Decorate1(Drink drink) { super(drink); } @Override String getDescription() { return "Decorate2" + "/" + drink.getDescription(); } @Override int cost() { return 1 + drink.cost(); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.mock.web; import java.io.IOException; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.FilterConfig; import jakarta.servlet.Servlet; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Test fixture for {@link MockFilterChain}. * * @author Rob Winch */ class MockFilterChainTests { private ServletRequest request; private ServletResponse response; @BeforeEach void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); } @Test void constructorNullServlet() { assertThatIllegalArgumentException().isThrownBy(() -> new MockFilterChain(null)); } @Test void constructorNullFilter() { assertThatIllegalArgumentException().isThrownBy(() -> new MockFilterChain(mock(), (Filter) null)); } @Test void doFilterNullRequest() throws Exception { MockFilterChain chain = new MockFilterChain(); assertThatIllegalArgumentException().isThrownBy(() -> chain.doFilter(null, this.response)); } @Test void doFilterNullResponse() throws Exception { MockFilterChain chain = new MockFilterChain(); assertThatIllegalArgumentException().isThrownBy(() -> chain.doFilter(this.request, null)); } @Test void doFilterEmptyChain() throws Exception { MockFilterChain chain = new MockFilterChain(); chain.doFilter(this.request, this.response); assertThat(chain.getRequest()).isEqualTo(request); assertThat(chain.getResponse()).isEqualTo(response); assertThatIllegalStateException() .isThrownBy(() -> chain.doFilter(this.request, this.response)) .withMessage("This FilterChain has already been called!"); } @Test void doFilterWithServlet() throws Exception { Servlet servlet = mock(); MockFilterChain chain = new MockFilterChain(servlet); chain.doFilter(this.request, this.response); verify(servlet).service(this.request, this.response); assertThatIllegalStateException() .isThrownBy(() -> chain.doFilter(this.request, this.response)) .withMessage("This FilterChain has already been called!"); } @Test void doFilterWithServletAndFilters() throws Exception { Servlet servlet = mock(); MockFilter filter2 = new MockFilter(servlet); MockFilter filter1 = new MockFilter(null); MockFilterChain chain = new MockFilterChain(servlet, filter1, filter2); chain.doFilter(this.request, this.response); assertThat(filter1.invoked).isTrue(); assertThat(filter2.invoked).isTrue(); verify(servlet).service(this.request, this.response); assertThatIllegalStateException() .isThrownBy(() -> chain.doFilter(this.request, this.response)) .withMessage("This FilterChain has already been called!"); } private static class MockFilter implements Filter { private final Servlet servlet; private boolean invoked; public MockFilter(Servlet servlet) { this.servlet = servlet; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { this.invoked = true; if (this.servlet != null) { this.servlet.service(request, response); } else { chain.doFilter(request, response); } } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } } }
package com.qfc.yft.data; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.qfc.yft.YftApplication; import com.qfc.yft.YftValues; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class LocalSearchHistoryManager { private static LocalSearchHistoryManager manager; private LocalSearchHistoryManager(){ pref = YftApplication.app().getSharedPreferences(YftValues.PREF_LOCAL, Context.MODE_PRIVATE); map = new HashMap<String, List<String>>(); }; public static LocalSearchHistoryManager getInstance(){ if(null==manager) manager = new LocalSearchHistoryManager(); return manager; } private final String DIVIDER = "&:&"; SharedPreferences pref; Editor edit; Map<String, List<String>> map; public Editor edit(){ if(null==edit){ edit = pref.edit(); } return edit; } public void add(String word,String type){ List<String> list = initList(type); if(!list.contains(word))list.add(word); edit().putString(type, convertListToString(list)).commit(); } public List<String> getList(String type){ return trimList(initList(type)); } public void deleteAll(){ edit().clear().commit(); map.clear(); } private List<String> initList(String type){ List<String > list= map.get(type); if(null==list) { list = convertStringToList(type); map.put(type, list); } return list; } private List<String> trimList(List<String> list){ while(list.size()>10){ list.remove(0); } return list; } private List<String> convertStringToList(String type) { List<String> list; list = new LinkedList<String>(); String resultStr = pref.getString(type, ""); if(!resultStr.isEmpty()){ for(String s:resultStr.split(DIVIDER)){ list.add(s); } } return list; } private String convertListToString(List<String> list){ String result=""; for(String s:list){ result+=s+DIVIDER; } return result; } }
package com.iteima; /* */ public class PopularSetting { public static void main(String[] args) { } public void run(String s){ System.out.println("PopularSetting.run"); System.out.println("s = " + s); } }
/* Copyright 2015 The jeo project. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jeo.js; import com.google.common.base.Strings; import jline.console.ConsoleReader; import jline.console.UserInterruptException; import java.io.IOException; /** * The jeojs Read Eval Print loop console. */ public abstract class Repl { ConsoleReader console; State state; public Repl(ConsoleReader console) { this.console = console; state = new State(); } public void start() throws IOException { while(true) { try { String line = console.readLine(state.prompt()); state.feed(line); if (state.balanced()) { handle(state.input(true)); } } catch(UserInterruptException stop) { if (!Strings.isNullOrEmpty(stop.getPartialLine())) { // cancel the current input console.killLine(); continue; } if (state.stopping()) { System.exit(0); } else { console.println(); console.println("(^C again to quit)"); state.stop(); } } } } protected abstract void handle(String input); class State { int balance = 0; StringBuilder buffer = new StringBuilder(); boolean stop = false; String prompt() { return balance == 0 ? "> " : "... "; } State feed(String input) { stop = false; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); switch(c) { case '(': case '{': case '[': balance++; break; case ')': case ']': case '}': balance--; } } buffer.append(input); return this; } State stop() { stop = true; return this; } boolean balanced() { return balance == 0; } boolean stopping() { return stop; } String input(boolean clear) { String input = buffer.toString(); if (clear) { clear(); } return input; } State clear() { buffer.setLength(0); return this; } } }
package com.diegov22.alarma; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.os.SystemClock; import android.widget.CompoundButton; import android.widget.Toast; import android.widget.ToggleButton; import static android.content.Context.ALARM_SERVICE; import static android.content.Context.NOTIFICATION_SERVICE; public class MainActivity extends AppCompatActivity { private NotificationManager mNotificationManager; private static final int NOTIFICATION_ID = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); ToggleButton alarmToggle = findViewById(R.id.alarmToggle); //set up the notification broadcast intent Intent notifyIntent = new Intent(this, alarmReceiver.class); //check if the alarm is already set, and check the toggle accordingly boolean alarmUp = (PendingIntent.getBroadcast(this, 0, notifyIntent, PendingIntent.FLAG_NO_CREATE) != null); alarmToggle.setChecked(alarmUp); //set up the pendingintent fot alarmanager final PendingIntent notifyPendingIntent = PendingIntent.getBroadcast(this, NOTIFICATION_ID, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT); alarmToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compundButton, boolean isChecked){ String toastessage; if (isChecked){ long triggerTime = SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_FIFTEEN_MINUTES; long repeatInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES; //If the toglle is turned on, set the repeating alarm with a 15 minutes interval alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, repeatInterval, notifyPendingIntent); //set the toast message for the "on" cas toastessage = getString(R.string.alarm_on_toast); }else{ //cancel the alarm and notification if the alarm is turned off alarmManager.cancel(notifyPendingIntent); mNotificationManager.cancelAll(); //set the toast message for the "off" cas toastessage = getString(R.string.alarm_off_toast); } Toast.makeText(MainActivity.this, toastessage, Toast.LENGTH_LONG).show(); } }); } }
package com.oa.lucene.controller; import java.io.IOException; import java.text.ParseException; import java.util.List; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONObject; import com.oa.lucene.crawl.NTES; import com.oa.lucene.entity.News; @Controller @RequestMapping(value = "/crawl/manager") public class CrawlController { @Autowired private IndexWriter indexWriter; @SuppressWarnings("deprecation") @ResponseBody @RequestMapping(value = "/ntes", method = RequestMethod.GET) public String ntes(String category) throws Exception { // 抓取网易新闻头条 List<News> list = NTES.crawl163LatestNews(category); // 重复抓取会重复添加索引 indexWriter.deleteAll(); Document doc = null; for (News news : list) { doc = new Document(); Field title = new Field("title", news.getTitle(), Field.Store.YES, Field.Index.ANALYZED); Field content = new Field("content", news.getContent(), Field.Store.YES, Field.Index.ANALYZED); Field shortContent = new Field("shortContent", news.getShortContent(), Field.Store.YES, Field.Index.NO); Field url = new Field("url", news.getUrl(), Field.Store.YES, Field.Index.NO); Field date = new Field("date", news.getDate(), Field.Store.YES, Field.Index.NO); doc.add(title); doc.add(content); doc.add(shortContent); doc.add(url); doc.add(date); indexWriter.addDocument(doc); } // indexWriter.close()关闭索引 // 提交索引不关闭indexWriter的情况下提交更改,从而保留writer至下一次提交时刻。 indexWriter.commit(); return JSONObject.toJSONString(list); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.stereotype; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that the annotated class is a <em>component</em>. * * <p>Such classes are considered as candidates for auto-detection * when using annotation-based configuration and classpath scanning. * * <p>A component may optionally specify a logical component name via the * {@link #value value} attribute of this annotation. * * <p>Other class-level annotations may be considered as identifying * a component as well, typically a special kind of component &mdash; * for example, the {@link Repository @Repository} annotation or AspectJ's * {@link org.aspectj.lang.annotation.Aspect @Aspect} annotation. Note, however, * that the {@code @Aspect} annotation does not automatically make a class * eligible for classpath scanning. * * <p>Any annotation meta-annotated with {@code @Component} is considered a * <em>stereotype</em> annotation which makes the annotated class eligible for * classpath scanning. For example, {@link Service @Service}, * {@link Controller @Controller}, and {@link Repository @Repository} are * stereotype annotations. Stereotype annotations may also support configuration * of a logical component name by overriding the {@link #value} attribute of this * annotation via {@link org.springframework.core.annotation.AliasFor @AliasFor}. * * <p>As of Spring Framework 6.1, support for configuring the name of a stereotype * component by convention (i.e., via a {@code String value()} attribute without * {@code @AliasFor}) is deprecated and will be removed in a future version of the * framework. Consequently, custom stereotype annotations must use {@code @AliasFor} * to declare an explicit alias for this annotation's {@link #value} attribute. * See the source code declaration of {@link Repository#value()} and * {@link org.springframework.web.bind.annotation.ControllerAdvice#name() * ControllerAdvice.name()} for concrete examples. * * @author Mark Fisher * @author Sam Brannen * @since 2.5 * @see Repository * @see Service * @see Controller * @see org.springframework.context.annotation.ClassPathBeanDefinitionScanner */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Indexed public @interface Component { /** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean name in case of an autodetected component. * @return the suggested component name, if any (or empty String otherwise) */ String value() default ""; }
package Business_Layer.Trace; import java.util.Observable; public class PersonalPage extends Observable{ /* כאשר רוצים לשנות משהו בתוך הפונקציה נקרא לשיטות: public change(){ setChanged(); notifyObservers(); } כדי להוסיף נושא מסוים עושים: subject.addObserver(צופה); */ }
package test; import java.util.List; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class CopyHW { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); ChromeDriver driver=new ChromeDriver(); //Load the URL driver.get("https://www.irctc.co.in/eticketing/loginHome.jsf"); //maximize the window driver.manage().window().maximize(); driver.findElementByLinkText("Sign up").click(); WebElement country =driver.findElementById("userRegistrationForm:countries"); Select dropdown=new Select(country); List<WebElement> allob=dropdown.getOptions(); for (WebElement eachop : allob) { System.out.println(eachop.getText()); } /*int i = 0; i++;*/ } }
package com.citibank.ods.persistence.pl.dao; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.entity.pl.BaseTplMrDocPrvtEntity; import com.citibank.ods.entity.pl.TplMrDocPrvtMovEntity; /** * @author m.nakamura * * Interface para acesso ao banco de dados de movimento de Memória de Risco. */ public interface TplMrDocPrvtMovDAO extends BaseTplMrDocPrvtDAO { /** * Insere dados na tabela de Memória de Risco. * * @param mrDocPrvtMovEntity_ - Entidade com os dados a serem inseridos. */ public void insert(TplMrDocPrvtMovEntity mrDocPrvtMovEntity_); /** * Verifica se MR existe em movimento. * * @param mrDocPrvtMovEntity_ - Entidade com MR a ser verificado. * @return true se MR existe em movimento, false caso contrário. */ public boolean existsMovement(TplMrDocPrvtMovEntity mrDocPrvtMovEntity_); /** * Retorna Data Set com os campos do grid da consulta em lista. * * @param mrDocCode_ - Código Documento MR * @param mrDocText_ - Descrição Documento MR * @param mrInvstCurAcctInd_ - Indicador de conta CCI * @param custNbr_ - Número do cliente * @param curAcctNbr_ - Número da conta corrente * @param lastUpdUserId_ - Nome do usuário da última atualização * @param lastUpdDate_ - Data da última atualização * @return DataSet - Data Set com os campos do grid da consulta em lista. */ public DataSet list( BigInteger mrDocCode_, String mrDocText_, String mrInvstCurAcctInd_, BigInteger custNbr_, String custName_, BigInteger curAcctNbr_, String lastUpdUserId_, Date lastUpdDate_, BigInteger prodAcctCode_, BigInteger prodAcctUnderCode_ ); public ArrayList list(BigInteger prodAcctCode_,BigInteger prodAcctUnderCode_ ); /** * Atualiza a tabela de Movemento de Memo de Risco. * * @param mrDocPrvtMovEntity_ - Entidade com os dados a serem atualizados. */ public void update(TplMrDocPrvtMovEntity mrDocPrvtMovEntity_); /** * Deleta registro da tabela de Movemento de Memo de Risco. * * @param mrDocPrvtMovEntity_ - Entidade com as chaves do registro a ser * deletado. */ public void delete(TplMrDocPrvtMovEntity mrDocPrvtMovEntity_); /** * Copia registro de Mov para Current. * * @param baseTplMrDocPrvtEntity_ - Entidade com as chaves do registro a ser * copiado. * @param lastAuthDate_ - Data da aprovação. * @param lastAuthUserId_ - Usuário da aprovação. */ public void copyFromMovToCurrent( BaseTplMrDocPrvtEntity baseTplMrDocPrvtEntity_, Date lastAuthDate, String lastAuthUserId); public BigInteger getNextVal(); public boolean findExists(BaseTplMrDocPrvtEntity baseTplMrDocPrvtEntity_); }