code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.model.item; import org.teleal.cling.support.model.Res; import org.teleal.cling.support.model.StorageMedium; import org.teleal.cling.support.model.container.Container; import java.util.List; import static org.teleal.cling.support.model.DIDLObject.Property.UPNP; /** * @author Christian Bauer */ public class Movie extends VideoItem { public static final Class CLASS = new Class("object.item.videoItem.movie"); public Movie() { setClazz(CLASS); } public Movie(Item other) { super(other); } public Movie(String id, Container parent, String title, String creator, Res... resource) { this(id, parent.getId(), title, creator, resource); } public Movie(String id, String parentID, String title, String creator, Res... resource) { super(id, parentID, title, creator, resource); setClazz(CLASS); } public StorageMedium getStorageMedium() { return getFirstPropertyValue(UPNP.STORAGE_MEDIUM.class); } public Movie setStorageMedium(StorageMedium storageMedium) { replaceFirstProperty(new UPNP.STORAGE_MEDIUM(storageMedium)); return this; } public Integer getDVDRegionCode() { return getFirstPropertyValue(UPNP.DVD_REGION_CODE.class); } public Movie setDVDRegionCode(Integer DVDRegionCode) { replaceFirstProperty(new UPNP.DVD_REGION_CODE(DVDRegionCode)); return this; } public String getChannelName() { return getFirstPropertyValue(UPNP.CHANNEL_NAME.class); } public Movie setChannelName(String channelName) { replaceFirstProperty(new UPNP.CHANNEL_NAME(channelName)); return this; } public String getFirstScheduledStartTime() { return getFirstPropertyValue(UPNP.SCHEDULED_START_TIME.class); } public String[] getScheduledStartTimes() { List<String> list = getPropertyValues(UPNP.SCHEDULED_START_TIME.class); return list.toArray(new String[list.size()]); } public Movie setScheduledStartTimes(String[] strings) { removeProperties(UPNP.SCHEDULED_START_TIME.class); for (String s : strings) { addProperty(new UPNP.SCHEDULED_START_TIME(s)); } return this; } public String getFirstScheduledEndTime() { return getFirstPropertyValue(UPNP.SCHEDULED_END_TIME.class); } public String[] getScheduledEndTimes() { List<String> list = getPropertyValues(UPNP.SCHEDULED_END_TIME.class); return list.toArray(new String[list.size()]); } public Movie setScheduledEndTimes(String[] strings) { removeProperties(UPNP.SCHEDULED_END_TIME.class); for (String s : strings) { addProperty(new UPNP.SCHEDULED_END_TIME(s)); } return this; } }
zzh84615-mycode
src/org/teleal/cling/support/model/item/Movie.java
Java
asf20
3,562
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.model.item; import org.teleal.cling.support.model.DIDLObject; import org.teleal.cling.support.model.DescMeta; import org.teleal.cling.support.model.Res; import org.teleal.cling.support.model.WriteStatus; import org.teleal.cling.support.model.container.Container; import java.util.ArrayList; import java.util.List; /** * @author Christian Bauer */ public class Item extends DIDLObject { protected String refID; public Item() { } public Item(Item other) { super(other); setRefID(other.getRefID()); } public Item(String id, String parentID, String title, String creator, boolean restricted, WriteStatus writeStatus, Class clazz, List<Res> resources, List<Property> properties, List<DescMeta> descMetadata) { super(id, parentID, title, creator, restricted, writeStatus, clazz, resources, properties, descMetadata); } public Item(String id, String parentID, String title, String creator, boolean restricted, WriteStatus writeStatus, Class clazz, List<Res> resources, List<Property> properties, List<DescMeta> descMetadata, String refID) { super(id, parentID, title, creator, restricted, writeStatus, clazz, resources, properties, descMetadata); this.refID = refID; } public Item(String id, Container parent, String title, String creator, DIDLObject.Class clazz) { this(id, parent.getId(), title, creator, false, null, clazz, new ArrayList(), new ArrayList(), new ArrayList()); } public Item(String id, Container parent, String title, String creator, DIDLObject.Class clazz, String refID) { this(id, parent.getId(), title, creator, false, null, clazz, new ArrayList(), new ArrayList(), new ArrayList(), refID); } public Item(String id, String parentID, String title, String creator, DIDLObject.Class clazz) { this(id, parentID, title, creator, false, null, clazz, new ArrayList(), new ArrayList(), new ArrayList()); } public Item(String id, String parentID, String title, String creator, DIDLObject.Class clazz, String refID) { this(id, parentID, title, creator, false, null, clazz, new ArrayList(), new ArrayList(), new ArrayList(), refID); } public String getRefID() { return refID; } public void setRefID(String refID) { this.refID = refID; } }
zzh84615-mycode
src/org/teleal/cling/support/model/item/Item.java
Java
asf20
3,088
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.model.item; import org.teleal.cling.support.model.Res; import static org.teleal.cling.support.model.DIDLObject.Property.UPNP; /** * @author Christian Bauer */ public class AudioBroadcast extends AudioItem { public static final Class CLASS = new Class("object.item.audioItem.audioBroadcast"); public AudioBroadcast() { setClazz(CLASS); } public AudioBroadcast(Item other) { super(other); } public AudioBroadcast(String id, String parentID, String title, String creator, Res... resource) { super(id, parentID, title, creator, resource); setClazz(CLASS); } public String getRegion() { return getFirstPropertyValue(UPNP.REGION.class); } public AudioBroadcast setRegion(String region) { replaceFirstProperty(new UPNP.REGION(region)); return this; } public String getRadioCallSign() { return getFirstPropertyValue(UPNP.RADIO_CALL_SIGN.class); } public AudioBroadcast setRadioCallSign(String radioCallSign) { replaceFirstProperty(new UPNP.RADIO_CALL_SIGN(radioCallSign)); return this; } public String getRadioStationID() { return getFirstPropertyValue(UPNP.RADIO_STATION_ID.class); } public AudioBroadcast setRadioStationID(String radioStationID) { replaceFirstProperty(new UPNP.RADIO_STATION_ID(radioStationID)); return this; } public String getRadioBand() { return getFirstPropertyValue(UPNP.RADIO_BAND.class); } public AudioBroadcast setRadioBand(String radioBand) { replaceFirstProperty(new UPNP.RADIO_BAND(radioBand)); return this; } public Integer getChannelNr() { return getFirstPropertyValue(UPNP.CHANNEL_NR.class); } public AudioBroadcast setChannelNr(Integer channelNr) { replaceFirstProperty(new UPNP.CHANNEL_NR(channelNr)); return this; } }
zzh84615-mycode
src/org/teleal/cling/support/model/item/AudioBroadcast.java
Java
asf20
2,683
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.model.item; import org.teleal.cling.support.model.Person; import org.teleal.cling.support.model.PersonWithRole; import org.teleal.cling.support.model.Res; import org.teleal.cling.support.model.container.Container; import java.net.URI; import java.util.Arrays; import java.util.List; import static org.teleal.cling.support.model.DIDLObject.Property.DC; import static org.teleal.cling.support.model.DIDLObject.Property.UPNP; /** * @author Christian Bauer */ public class VideoItem extends Item { public static final Class CLASS = new Class("object.item.videoItem"); public VideoItem() { setClazz(CLASS); } public VideoItem(Item other) { super(other); } public VideoItem(String id, Container parent, String title, String creator, Res... resource) { this(id, parent.getId(), title, creator, resource); } public VideoItem(String id, String parentID, String title, String creator, Res... resource) { super(id, parentID, title, creator, CLASS); if (resource != null) { getResources().addAll(Arrays.asList(resource)); } } public String getFirstGenre() { return getFirstPropertyValue(UPNP.GENRE.class); } public String[] getGenres() { List<String> list = getPropertyValues(UPNP.GENRE.class); return list.toArray(new String[list.size()]); } public VideoItem setGenres(String[] genres) { removeProperties(UPNP.GENRE.class); for (String genre : genres) { addProperty(new UPNP.GENRE(genre)); } return this; } public String getDescription() { return getFirstPropertyValue(DC.DESCRIPTION.class); } public VideoItem setDescription(String description) { replaceFirstProperty(new DC.DESCRIPTION(description)); return this; } public String getLongDescription() { return getFirstPropertyValue(UPNP.LONG_DESCRIPTION.class); } public VideoItem setLongDescription(String description) { replaceFirstProperty(new UPNP.LONG_DESCRIPTION(description)); return this; } public Person getFirstProducer() { return getFirstPropertyValue(UPNP.PRODUCER.class); } public Person[] getProducers() { List<Person> list = getPropertyValues(UPNP.PRODUCER.class); return list.toArray(new Person[list.size()]); } public VideoItem setProducers(Person[] persons) { removeProperties(UPNP.PRODUCER.class); for (Person p : persons) { addProperty(new UPNP.PRODUCER(p)); } return this; } public String getRating() { return getFirstPropertyValue(UPNP.RATING.class); } public VideoItem setRating(String rating) { replaceFirstProperty(new UPNP.RATING(rating)); return this; } public PersonWithRole getFirstActor() { return getFirstPropertyValue(UPNP.ACTOR.class); } public PersonWithRole[] getActors() { List<PersonWithRole> list = getPropertyValues(UPNP.ACTOR.class); return list.toArray(new PersonWithRole[list.size()]); } public VideoItem setActors(PersonWithRole[] persons) { removeProperties(UPNP.ACTOR.class); for (PersonWithRole p : persons) { addProperty(new UPNP.ACTOR(p)); } return this; } public Person getFirstDirector() { return getFirstPropertyValue(UPNP.DIRECTOR.class); } public Person[] getDirectors() { List<Person> list = getPropertyValues(UPNP.DIRECTOR.class); return list.toArray(new Person[list.size()]); } public VideoItem setDirectors(Person[] persons) { removeProperties(UPNP.DIRECTOR.class); for (Person p : persons) { addProperty(new UPNP.DIRECTOR(p)); } return this; } public Person getFirstPublisher() { return getFirstPropertyValue(DC.PUBLISHER.class); } public Person[] getPublishers() { List<Person> list = getPropertyValues(DC.PUBLISHER.class); return list.toArray(new Person[list.size()]); } public VideoItem setPublishers(Person[] publishers) { removeProperties(DC.PUBLISHER.class); for (Person publisher : publishers) { addProperty(new DC.PUBLISHER(publisher)); } return this; } public String getLanguage() { return getFirstPropertyValue(DC.LANGUAGE.class); } public VideoItem setLanguage(String language) { replaceFirstProperty(new DC.LANGUAGE(language)); return this; } public URI getFirstRelation() { return getFirstPropertyValue(DC.RELATION.class); } public URI[] getRelations() { List<URI> list = getPropertyValues(DC.RELATION.class); return list.toArray(new URI[list.size()]); } public VideoItem setRelations(URI[] relations) { removeProperties(DC.RELATION.class); for (URI relation : relations) { addProperty(new DC.RELATION(relation)); } return this; } }
zzh84615-mycode
src/org/teleal/cling/support/model/item/VideoItem.java
Java
asf20
5,849
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.model.item; import org.teleal.cling.support.model.Person; import org.teleal.cling.support.model.Res; import org.teleal.cling.support.model.container.Container; import java.net.URI; import java.util.Arrays; import java.util.List; import static org.teleal.cling.support.model.DIDLObject.Property.DC; import static org.teleal.cling.support.model.DIDLObject.Property.UPNP; /** * @author Christian Bauer */ public class AudioItem extends Item { public static final Class CLASS = new Class("object.item.audioItem"); public AudioItem() { setClazz(CLASS); } public AudioItem(Item other) { super(other); } public AudioItem(String id, Container parent, String title, String creator, Res... resource) { this(id, parent.getId(), title, creator, resource); } public AudioItem(String id, String parentID, String title, String creator, Res... resource) { super(id, parentID, title, creator, CLASS); if (resource != null) { getResources().addAll(Arrays.asList(resource)); } } public String getFirstGenre() { return getFirstPropertyValue(UPNP.GENRE.class); } public String[] getGenres() { List<String> list = getPropertyValues(UPNP.GENRE.class); return list.toArray(new String[list.size()]); } public AudioItem setGenres(String[] genres) { removeProperties(UPNP.GENRE.class); for (String genre : genres) { addProperty(new UPNP.GENRE(genre)); } return this; } public String getDescription() { return getFirstPropertyValue(DC.DESCRIPTION.class); } public AudioItem setDescription(String description) { replaceFirstProperty(new DC.DESCRIPTION(description)); return this; } public String getLongDescription() { return getFirstPropertyValue(UPNP.LONG_DESCRIPTION.class); } public AudioItem setLongDescription(String description) { replaceFirstProperty(new UPNP.LONG_DESCRIPTION(description)); return this; } public Person getFirstPublisher() { return getFirstPropertyValue(DC.PUBLISHER.class); } public Person[] getPublishers() { List<Person> list = getPropertyValues(DC.PUBLISHER.class); return list.toArray(new Person[list.size()]); } public AudioItem setPublishers(Person[] publishers) { removeProperties(DC.PUBLISHER.class); for (Person publisher : publishers) { addProperty(new DC.PUBLISHER(publisher)); } return this; } public URI getFirstRelation() { return getFirstPropertyValue(DC.RELATION.class); } public URI[] getRelations() { List<URI> list = getPropertyValues(DC.RELATION.class); return list.toArray(new URI[list.size()]); } public AudioItem setRelations(URI[] relations) { removeProperties(DC.RELATION.class); for (URI relation : relations) { addProperty(new DC.RELATION(relation)); } return this; } public String getLanguage() { return getFirstPropertyValue(DC.LANGUAGE.class); } public AudioItem setLanguage(String language) { replaceFirstProperty(new DC.LANGUAGE(language)); return this; } public String getFirstRights() { return getFirstPropertyValue(DC.RIGHTS.class); } public String[] getRights() { List<String> list = getPropertyValues(DC.RIGHTS.class); return list.toArray(new String[list.size()]); } public AudioItem setRights(String[] rights) { removeProperties(DC.RIGHTS.class); for (String right : rights) { addProperty(new DC.RIGHTS(right)); } return this; } }
zzh84615-mycode
src/org/teleal/cling/support/model/item/AudioItem.java
Java
asf20
4,539
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.model.item; import org.teleal.cling.support.model.Person; import org.teleal.cling.support.model.PersonWithRole; import org.teleal.cling.support.model.Res; import org.teleal.cling.support.model.StorageMedium; import org.teleal.cling.support.model.container.Container; import java.net.URI; import java.util.Arrays; import java.util.List; import static org.teleal.cling.support.model.DIDLObject.Property.DC; import static org.teleal.cling.support.model.DIDLObject.Property.UPNP; /** * @author Christian Bauer */ public class PlaylistItem extends Item { public static final Class CLASS = new Class("object.item.playlistItem"); public PlaylistItem() { setClazz(CLASS); } public PlaylistItem(Item other) { super(other); } public PlaylistItem(String id, Container parent, String title, String creator, Res... resource) { this(id, parent.getId(), title, creator, resource); } public PlaylistItem(String id, String parentID, String title, String creator, Res... resource) { super(id, parentID, title, creator, CLASS); if (resource != null) { getResources().addAll(Arrays.asList(resource)); } } public PersonWithRole getFirstArtist() { return getFirstPropertyValue(UPNP.ARTIST.class); } public PersonWithRole[] getArtists() { List<PersonWithRole> list = getPropertyValues(UPNP.ARTIST.class); return list.toArray(new PersonWithRole[list.size()]); } public PlaylistItem setArtists(PersonWithRole[] artists) { removeProperties(UPNP.ARTIST.class); for (PersonWithRole artist : artists) { addProperty(new UPNP.ARTIST(artist)); } return this; } public String getFirstGenre() { return getFirstPropertyValue(UPNP.GENRE.class); } public String[] getGenres() { List<String> list = getPropertyValues(UPNP.GENRE.class); return list.toArray(new String[list.size()]); } public PlaylistItem setGenres(String[] genres) { removeProperties(UPNP.GENRE.class); for (String genre : genres) { addProperty(new UPNP.GENRE(genre)); } return this; } public String getDescription() { return getFirstPropertyValue(DC.DESCRIPTION.class); } public PlaylistItem setDescription(String description) { replaceFirstProperty(new DC.DESCRIPTION(description)); return this; } public String getLongDescription() { return getFirstPropertyValue(UPNP.LONG_DESCRIPTION.class); } public PlaylistItem setLongDescription(String description) { replaceFirstProperty(new UPNP.LONG_DESCRIPTION(description)); return this; } public String getLanguage() { return getFirstPropertyValue(DC.LANGUAGE.class); } public PlaylistItem setLanguage(String language) { replaceFirstProperty(new DC.LANGUAGE(language)); return this; } public StorageMedium getStorageMedium() { return getFirstPropertyValue(UPNP.STORAGE_MEDIUM.class); } public PlaylistItem setStorageMedium(StorageMedium storageMedium) { replaceFirstProperty(new UPNP.STORAGE_MEDIUM(storageMedium)); return this; } public String getDate() { return getFirstPropertyValue(DC.DATE.class); } public PlaylistItem setDate(String date) { replaceFirstProperty(new DC.DATE(date)); return this; } }
zzh84615-mycode
src/org/teleal/cling/support/model/item/PlaylistItem.java
Java
asf20
4,246
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.model.item; import org.teleal.cling.support.model.Person; import org.teleal.cling.support.model.PersonWithRole; import org.teleal.cling.support.model.Res; import org.teleal.cling.support.model.StorageMedium; import org.teleal.cling.support.model.container.Container; import java.util.List; import static org.teleal.cling.support.model.DIDLObject.Property.DC; import static org.teleal.cling.support.model.DIDLObject.Property.UPNP; /** * @author Christian Bauer */ public class MusicTrack extends AudioItem { public static final Class CLASS = new Class("object.item.audioItem.musicTrack"); public MusicTrack() { setClazz(CLASS); } public MusicTrack(Item other) { super(other); } public MusicTrack(String id, Container parent, String title, String creator, String album, String artist, Res... resource) { this(id, parent.getId(), title, creator, album, artist, resource); } public MusicTrack(String id, Container parent, String title, String creator, String album, PersonWithRole artist, Res... resource) { this(id, parent.getId(), title, creator, album, artist, resource); } public MusicTrack(String id, String parentID, String title, String creator, String album, String artist, Res... resource) { this(id, parentID, title, creator, album, new PersonWithRole(artist), resource); } public MusicTrack(String id, String parentID, String title, String creator, String album, PersonWithRole artist, Res... resource) { super(id, parentID, title, creator, resource); setClazz(CLASS); if (album != null) setAlbum(album); if (artist != null) addProperty(new UPNP.ARTIST(artist)); } public PersonWithRole getFirstArtist() { return getFirstPropertyValue(UPNP.ARTIST.class); } public PersonWithRole[] getArtists() { List<PersonWithRole> list = getPropertyValues(UPNP.ARTIST.class); return list.toArray(new PersonWithRole[list.size()]); } public MusicTrack setArtists(PersonWithRole[] artists) { removeProperties(UPNP.ARTIST.class); for (PersonWithRole artist : artists) { addProperty(new UPNP.ARTIST(artist)); } return this; } public String getAlbum() { return getFirstPropertyValue(UPNP.ALBUM.class); } public MusicTrack setAlbum(String album) { replaceFirstProperty(new UPNP.ALBUM(album)); return this; } public Integer getOriginalTrackNumber() { return getFirstPropertyValue(UPNP.ORIGINAL_TRACK_NUMBER.class); } public MusicTrack setOriginalTrackNumber(Integer number) { replaceFirstProperty(new UPNP.ORIGINAL_TRACK_NUMBER(number)); return this; } public String getFirstPlaylist() { return getFirstPropertyValue(UPNP.PLAYLIST.class); } public String[] getPlaylists() { List<String> list = getPropertyValues(UPNP.PLAYLIST.class); return list.toArray(new String[list.size()]); } public MusicTrack setPlaylists(String[] playlists) { removeProperties(UPNP.PLAYLIST.class); for (String s : playlists) { addProperty(new UPNP.PLAYLIST(s)); } return this; } public StorageMedium getStorageMedium() { return getFirstPropertyValue(UPNP.STORAGE_MEDIUM.class); } public MusicTrack setStorageMedium(StorageMedium storageMedium) { replaceFirstProperty(new UPNP.STORAGE_MEDIUM(storageMedium)); return this; } public Person getFirstContributor() { return getFirstPropertyValue(DC.CONTRIBUTOR.class); } public Person[] getContributors() { List<Person> list = getPropertyValues(DC.CONTRIBUTOR.class); return list.toArray(new Person[list.size()]); } public MusicTrack setContributors(Person[] contributors) { removeProperties(DC.CONTRIBUTOR.class); for (Person p : contributors) { addProperty(new DC.CONTRIBUTOR(p)); } return this; } public String getDate() { return getFirstPropertyValue(DC.DATE.class); } public MusicTrack setDate(String date) { replaceFirstProperty(new DC.DATE(date)); return this; } }
zzh84615-mycode
src/org/teleal/cling/support/model/item/MusicTrack.java
Java
asf20
5,050
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.teleal.cling.support.model.item; import org.teleal.cling.support.model.Res; import org.teleal.cling.support.model.container.Container; import java.net.URI; import static org.teleal.cling.support.model.DIDLObject.Property.UPNP; /** * @author Christian Bauer */ public class VideoBroadcast extends VideoItem { public static final Class CLASS = new Class("object.item.videoItem.videoBroadcast"); public VideoBroadcast() { setClazz(CLASS); } public VideoBroadcast(Item other) { super(other); } public VideoBroadcast(String id, Container parent, String title, String creator, Res... resource) { this(id, parent.getId(), title, creator, resource); } public VideoBroadcast(String id, String parentID, String title, String creator, Res... resource) { super(id, parentID, title, creator, resource); setClazz(CLASS); } public URI getIcon() { return getFirstPropertyValue(UPNP.ICON.class); } public VideoBroadcast setIcon(URI icon) { replaceFirstProperty(new UPNP.ICON(icon)); return this; } public String getRegion() { return getFirstPropertyValue(UPNP.REGION.class); } public VideoBroadcast setRegion(String region) { replaceFirstProperty(new UPNP.REGION(region)); return this; } public Integer getChannelNr() { return getFirstPropertyValue(UPNP.CHANNEL_NR.class); } public VideoBroadcast setChannelNr(Integer channelNr) { replaceFirstProperty(new UPNP.CHANNEL_NR(channelNr)); return this; } }
zzh84615-mycode
src/org/teleal/cling/support/model/item/VideoBroadcast.java
Java
asf20
2,335
package com.wireme.player; import java.io.IOException; import javax.crypto.NullCipher; import com.wireme.R; import android.app.Activity; import android.content.Intent; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnErrorListener; import android.media.MediaPlayer.OnInfoListener; import android.media.MediaPlayer.OnPreparedListener; import android.media.MediaPlayer.OnSeekCompleteListener; import android.media.MediaPlayer.OnVideoSizeChangedListener; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.LinearLayout; import android.widget.MediaController; public class GPlayer extends Activity implements OnCompletionListener, OnErrorListener, OnInfoListener, OnPreparedListener, OnSeekCompleteListener, OnVideoSizeChangedListener, SurfaceHolder.Callback, MediaController.MediaPlayerControl { Display currentDisplay; SurfaceView surfaceView; SurfaceHolder surfaceHolder; MediaPlayer mediaPlayer; MediaController mediaController; int videoWidth = 0; int videoHeight = 0; boolean readyToPlay = false; String playURI; public final static String LOGTAG = "Gnap-GPlayer"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.gplayer); surfaceView = (SurfaceView) findViewById(R.id.gplayer_surfaceview); surfaceHolder = surfaceView.getHolder(); surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mediaPlayer = new MediaPlayer(); mediaPlayer.setOnCompletionListener(this); mediaPlayer.setOnErrorListener(this); mediaPlayer.setOnInfoListener(this); mediaPlayer.setOnPreparedListener(this); mediaPlayer.setOnSeekCompleteListener(this); mediaPlayer.setOnVideoSizeChangedListener(this); mediaController = new MediaController(this); Intent intent = getIntent(); playURI = intent.getStringExtra("playURI"); try { mediaPlayer.setDataSource(playURI); } catch (IllegalArgumentException e) { Log.v(LOGTAG, e.getMessage()); finish(); } catch (IllegalStateException e) { Log.v(LOGTAG, e.getMessage()); finish(); } catch (IOException e) { Log.v(LOGTAG, e.getMessage()); finish(); } currentDisplay = getWindowManager().getDefaultDisplay(); } @Override protected void onPause() { super.onPause(); } @Override protected void onStop() { super.onStop(); mediaPlayer.stop(); } @Override protected void onDestroy() { super.onDestroy(); if( mediaPlayer !=null ) { mediaPlayer.release(); mediaPlayer = null; } } @Override public boolean onTouchEvent(MotionEvent ev) { if (mediaController.isShowing()) { mediaController.hide(); } else { mediaController.show(10000); } return false; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub Log.v(LOGTAG, "surfaceChanged Called"); } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub Log.v(LOGTAG, "surfaceCreated Called"); mediaPlayer.setDisplay(holder); try { mediaPlayer.prepare(); } catch (IllegalStateException e) { Log.v(LOGTAG, e.getMessage()); finish(); } catch (IOException e) { Log.v(LOGTAG, e.getMessage()); finish(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub Log.v(LOGTAG, "surfaceDestroyed Called"); } @Override public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { // TODO Auto-generated method stub Log.v(LOGTAG, "onVideoSizeChanged Called"); } @Override public void onSeekComplete(MediaPlayer mp) { // TODO Auto-generated method stub Log.v(LOGTAG, "onSeekComplete Called"); } @Override public void onPrepared(MediaPlayer mp) { // TODO Auto-generated method stub Log.v(LOGTAG, "onPrepared Called"); videoWidth = mp.getVideoWidth(); videoHeight = mp.getVideoHeight(); if (videoWidth > currentDisplay.getWidth() || videoHeight > currentDisplay.getHeight()) { float heightRatio = (float) videoHeight / (float) currentDisplay.getHeight(); float widthRatio = (float) videoWidth / (float) currentDisplay.getWidth(); if (heightRatio > 1 || widthRatio > 1) { if (heightRatio > widthRatio) { videoHeight = (int) Math.ceil((float) videoHeight / (float) heightRatio); videoWidth = (int) Math.ceil((float) videoWidth / (float) heightRatio); } else { videoHeight = (int) Math.ceil((float) videoHeight / (float) widthRatio); videoWidth = (int) Math.ceil((float) videoWidth / (float) widthRatio); } } } surfaceView.setLayoutParams(new LinearLayout.LayoutParams(videoWidth, videoHeight)); mp.start(); mediaController.setMediaPlayer(this); mediaController.setAnchorView(this .findViewById(R.id.gplayer_surfaceview)); mediaController.setEnabled(true); mediaController.show(10000); } @Override public boolean onInfo(MediaPlayer mp, int whatInfo, int extra) { // TODO Auto-generated method stub if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) { Log.v(LOGTAG, "Media Info, Media Info Bad Interleaving " + extra); } else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) { Log.v(LOGTAG, "Media Info, Media Info Not Seekable " + extra); } else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) { Log.v(LOGTAG, "Media Info, Media Info Unknown " + extra); } else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) { Log.v(LOGTAG, "MediaInfo, Media Info Video Track Lagging " + extra); } else if (whatInfo == MediaPlayer.MEDIA_INFO_METADATA_UPDATE) { Log.v(LOGTAG, "MediaInfo, Media Info Metadata Update " + extra); } return false; } @Override public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub Log.v(LOGTAG, "onCompletion Called"); finish(); } @Override public boolean onError(MediaPlayer mp, int whatError, int extra) { // TODO Auto-generated method stub Log.v(LOGTAG, "onError Called"); if (whatError == MediaPlayer.MEDIA_ERROR_SERVER_DIED) { Log.v(LOGTAG, "Media Error, Server Died " + extra); } else if (whatError == MediaPlayer.MEDIA_ERROR_UNKNOWN) { Log.v(LOGTAG, "Media Error, Error Unknown " + extra); } return false; } @Override public boolean canPause() { // TODO Auto-generated method stub return true; } @Override public boolean canSeekBackward() { // TODO Auto-generated method stub return true; } @Override public boolean canSeekForward() { // TODO Auto-generated method stub return true; } @Override public int getBufferPercentage() { // TODO Auto-generated method stub return 0; } @Override public int getCurrentPosition() { // TODO Auto-generated method stub return mediaPlayer.getCurrentPosition(); } @Override public int getDuration() { // TODO Auto-generated method stub return mediaPlayer.getDuration(); } @Override public boolean isPlaying() { // TODO Auto-generated method stub return mediaPlayer.isPlaying(); } @Override public void pause() { // TODO Auto-generated method stub if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); } } @Override public void seekTo(int pos) { // TODO Auto-generated method stub mediaPlayer.seekTo(pos); } @Override public void start() { // TODO Auto-generated method stub mediaPlayer.start(); } }
zzh84615-mycode
src/com/wireme/player/GPlayer.java
Java
asf20
7,675
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wireme.util; import android.util.Log; import java.io.PrintWriter; import java.io.StringWriter; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; /* Taken from: http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob_plain;f=core/java/com/android/internal/logging/AndroidHandler.java;hb=c2ad241504fcaa12d4579d3b0b4038d1ca8d08c9 */ public class FixedAndroidHandler extends Handler { /** * Holds the formatter for all Android log handlers. */ private static final Formatter THE_FORMATTER = new Formatter() { @Override public String format(LogRecord r) { Throwable thrown = r.getThrown(); if (thrown != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); sw.write(r.getMessage()); sw.write("\n"); thrown.printStackTrace(pw); pw.flush(); return sw.toString(); } else { return r.getMessage(); } } }; /** * Constructs a new instance of the Android log handler. */ public FixedAndroidHandler() { setFormatter(THE_FORMATTER); } @Override public void close() { // No need to close, but must implement abstract method. } @Override public void flush() { // No need to flush, but must implement abstract method. } @Override public void publish(LogRecord record) { try { int level = getAndroidLevel(record.getLevel()); String tag = record.getLoggerName(); if (tag == null) { // Anonymous logger. tag = "null"; } else { // Tags must be <= 23 characters. int length = tag.length(); if (length > 23) { // Most loggers use the full class name. Try dropping the // package. int lastPeriod = tag.lastIndexOf("."); if (length - lastPeriod - 1 <= 23) { tag = tag.substring(lastPeriod + 1); } else { // Use last 23 chars. tag = tag.substring(tag.length() - 23); } } } /* ############################################################################################ Instead of using the perfectly fine java.util.logging API for setting the loggable levels, this call relies on a totally obscure "local.prop" file which you have to place on your device. By default, if you do not have that file and if you do not execute some magic "setprop" commands on your device, only INFO/WARN/ERROR is loggable. So whatever you do with java.util.logging.Logger.setLevel(...) doesn't have any effect. The debug messages might arrive here but they are dropped because you _also_ have to set the Android internal logging level with the aforementioned magic switches. Also, consider that you have to understand how a JUL logger name is mapped to the "tag" of the Android log. Basically, the whole cutting and cropping procedure above is what you have to memorize if you want to log with JUL and configure Android for debug output. I actually admire the pure evil of this setup, even Mr. Ceki can learn something! Commenting out these lines makes it all work as expected: if (!Log.isLoggable(tag, level)) { return; } ############################################################################################### */ String message = getFormatter().format(record); Log.println(level, tag, message); } catch (RuntimeException e) { Log.e("AndroidHandler", "Error logging message.", e); } } /** * Converts a {@link java.util.logging.Logger} logging level into an Android one. * * @param level The {@link java.util.logging.Logger} logging level. * * @return The resulting Android logging level. */ static int getAndroidLevel(Level level) { int value = level.intValue(); if (value >= 1000) { // SEVERE return Log.ERROR; } else if (value >= 900) { // WARNING return Log.WARN; } else if (value >= 800) { // INFO return Log.INFO; } else { return Log.DEBUG; } } }
zzh84615-mycode
src/com/wireme/util/FixedAndroidHandler.java
Java
asf20
5,353
package com.wireme.mediaserver; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; import org.teleal.cling.binding.annotations.AnnotationLocalServiceBinder; import org.teleal.cling.model.DefaultServiceManager; import org.teleal.cling.model.ValidationException; import org.teleal.cling.model.meta.DeviceDetails; import org.teleal.cling.model.meta.DeviceIdentity; import org.teleal.cling.model.meta.LocalDevice; import org.teleal.cling.model.meta.LocalService; import org.teleal.cling.model.meta.ManufacturerDetails; import org.teleal.cling.model.meta.ModelDetails; import org.teleal.cling.model.types.DeviceType; import org.teleal.cling.model.types.UDADeviceType; import org.teleal.cling.model.types.UDN; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.util.Log; public class MediaServer { private UDN udn = UDN.uniqueSystemIdentifier("GNaP-MediaServer"); private LocalDevice localDevice; private final static String deviceType = "MediaServer"; private final static int version = 1; private final static String LOGTAG = "GNaP-MediaServer"; private final static int port = 8192; private static InetAddress localAddress; public MediaServer(InetAddress localAddress) throws ValidationException { DeviceType type = new UDADeviceType(deviceType, version); DeviceDetails details = new DeviceDetails(android.os.Build.MODEL, new ManufacturerDetails(android.os.Build.MANUFACTURER), new ModelDetails("GNaP", "GNaP MediaServer for Android", "v1")); LocalService service = new AnnotationLocalServiceBinder() .read(ContentDirectoryService.class); service.setManager(new DefaultServiceManager<ContentDirectoryService>( service, ContentDirectoryService.class)); localDevice = new LocalDevice(new DeviceIdentity(udn), type, details, service); this.localAddress = localAddress; Log.v(LOGTAG, "MediaServer device created: "); Log.v(LOGTAG, "friendly name: " + details.getFriendlyName()); Log.v(LOGTAG, "manufacturer: " + details.getManufacturerDetails().getManufacturer()); Log.v(LOGTAG, "model: " + details.getModelDetails().getModelName()); //start http server try { new HttpServer(port); } catch (IOException ioe ) { System.err.println( "Couldn't start server:\n" + ioe ); System.exit( -1 ); } Log.v(LOGTAG, "Started Http Server on port " + port); } public LocalDevice getDevice() { return localDevice; } public String getAddress() { return localAddress.getHostAddress() + ":" + port; } }
zzh84615-mycode
src/com/wireme/mediaserver/MediaServer.java
Java
asf20
2,742
package com.wireme.mediaserver; import org.teleal.cling.support.model.container.Container; import org.teleal.cling.support.model.item.Item; public class ContentNode { private Container container; private Item item; private String id; private String fullPath; private boolean isItem; public ContentNode(String id, Container container) { this.id = id; this.container = container; this.fullPath = null; this.isItem = false; } public ContentNode(String id, Item item, String fullPath) { this.id = id; this.item = item; this.fullPath = fullPath; this.isItem = true; } public String getId() { return id; } public Container getContainer() { return container; } public Item getItem() { return item; } public String getFullPath() { if (isItem && fullPath != null) { return fullPath; } return null; } public boolean isItem() { return isItem; } }
zzh84615-mycode
src/com/wireme/mediaserver/ContentNode.java
Java
asf20
946
package com.wireme.mediaserver; import java.util.HashMap; import org.teleal.cling.support.model.WriteStatus; import org.teleal.cling.support.model.container.Container; public class ContentTree { public final static String ROOT_ID = "0"; public final static String VIDEO_ID = "1"; public final static String AUDIO_ID = "2"; public final static String IMAGE_ID = "3"; public final static String VIDEO_PREFIX = "video-item-"; public final static String AUDIO_PREFIX = "audio-item-"; public final static String IMAGE_PREFIX = "image-item-"; private static HashMap<String, ContentNode> contentMap = new HashMap<String, ContentNode>(); private static ContentNode rootNode = createRootNode(); public ContentTree() {}; protected static ContentNode createRootNode() { // create root container Container root = new Container(); root.setId(ROOT_ID); root.setParentID("-1"); root.setTitle("GNaP MediaServer root directory"); root.setCreator("GNaP Media Server"); root.setRestricted(true); root.setSearchable(true); root.setWriteStatus(WriteStatus.NOT_WRITABLE); root.setChildCount(0); ContentNode rootNode = new ContentNode(ROOT_ID, root); contentMap.put(ROOT_ID, rootNode); return rootNode; } public static ContentNode getRootNode() { return rootNode; } public static ContentNode getNode(String id) { if( contentMap.containsKey(id)) { return contentMap.get(id); } return null; } public static boolean hasNode(String id) { return contentMap.containsKey(id); } public static void addNode(String ID, ContentNode Node) { contentMap.put(ID, Node); } }
zzh84615-mycode
src/com/wireme/mediaserver/ContentTree.java
Java
asf20
1,615
package com.wireme.mediaserver; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Date; import java.util.Enumeration; import java.util.Vector; import java.util.Hashtable; import java.util.Locale; import java.util.Properties; import java.util.StringTokenizer; import java.util.TimeZone; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; /** * A simple, tiny, nicely embeddable HTTP 1.0 server in Java * Modified from NanoHTTPD, you can find it here * http://elonen.iki.fi/code/nanohttpd/ */ public class HttpServer { // ================================================== // API parts // ================================================== /** * Override this to customize the server.<p> * * (By default, this delegates to serveFile() and allows directory listing.) * * @param uri Percent-decoded URI without parameters, for example "/index.cgi" * @param method "GET", "POST" etc. * @param parms Parsed, percent decoded parameters from URI and, in case of POST, data. * @param header Header entries, percent decoded * @return HTTP response, see class Response for details */ public Response serve( String uri, String method, Properties header, Properties parms, Properties files ) { System.out.println( method + " '" + uri + "' " ); Enumeration e = header.propertyNames(); while ( e.hasMoreElements()) { String value = (String)e.nextElement(); System.out.println( " HDR: '" + value + "' = '" + header.getProperty( value ) + "'" ); } e = parms.propertyNames(); while ( e.hasMoreElements()) { String value = (String)e.nextElement(); System.out.println( " PRM: '" + value + "' = '" + parms.getProperty( value ) + "'" ); } e = files.propertyNames(); while ( e.hasMoreElements()) { String value = (String)e.nextElement(); System.out.println( " UPLOADED: '" + value + "' = '" + files.getProperty( value ) + "'" ); } //Map uri to acture file in ContentTree String itemId = uri.replaceFirst("/", ""); itemId = URLDecoder.decode(itemId); String newUri = null; if( ContentTree.hasNode(itemId) ) { ContentNode node = ContentTree.getNode(itemId); if (node.isItem()) { newUri = node.getFullPath(); } } if (newUri != null) uri = newUri; return serveFile( uri, header, myRootDir, false ); } /** * HTTP response. * Return one of these from serve(). */ public class Response { /** * Default constructor: response = HTTP_OK, data = mime = 'null' */ public Response() { this.status = HTTP_OK; } /** * Basic constructor. */ public Response( String status, String mimeType, InputStream data ) { this.status = status; this.mimeType = mimeType; this.data = data; } /** * Convenience method that makes an InputStream out of * given text. */ public Response( String status, String mimeType, String txt ) { this.status = status; this.mimeType = mimeType; try { this.data = new ByteArrayInputStream( txt.getBytes("UTF-8")); } catch ( java.io.UnsupportedEncodingException uee ) { uee.printStackTrace(); } } /** * Adds given line to the header. */ public void addHeader( String name, String value ) { header.put( name, value ); } /** * HTTP status code after processing, e.g. "200 OK", HTTP_OK */ public String status; /** * MIME type of content, e.g. "text/html" */ public String mimeType; /** * Data of the response, may be null. */ public InputStream data; /** * Headers for the HTTP response. Use addHeader() * to add lines. */ public Properties header = new Properties(); } /** * Some HTTP response status codes */ public static final String HTTP_OK = "200 OK", HTTP_PARTIALCONTENT = "206 Partial Content", HTTP_RANGE_NOT_SATISFIABLE = "416 Requested Range Not Satisfiable", HTTP_REDIRECT = "301 Moved Permanently", HTTP_FORBIDDEN = "403 Forbidden", HTTP_NOTFOUND = "404 Not Found", HTTP_BADREQUEST = "400 Bad Request", HTTP_INTERNALERROR = "500 Internal Server Error", HTTP_NOTIMPLEMENTED = "501 Not Implemented"; /** * Common mime types for dynamic content */ public static final String MIME_PLAINTEXT = "text/plain", MIME_HTML = "text/html", MIME_DEFAULT_BINARY = "application/octet-stream", MIME_XML = "text/xml"; // ================================================== // Socket & server code // ================================================== /** * Starts a HTTP server to given port.<p> * Throws an IOException if the socket is already in use */ public HttpServer( int port ) throws IOException { myTcpPort = port; this.myRootDir = new File("/"); myServerSocket = new ServerSocket( myTcpPort ); myThread = new Thread( new Runnable() { public void run() { try { while( true ) new HTTPSession( myServerSocket.accept()); } catch ( IOException ioe ) {} } }); myThread.setDaemon( true ); myThread.start(); } /** * Stops the server. */ public void stop() { try { myServerSocket.close(); myThread.join(); } catch ( IOException ioe ) {} catch ( InterruptedException e ) {} } /** * Handles one session, i.e. parses the HTTP request * and returns the response. */ private class HTTPSession implements Runnable { public HTTPSession( Socket s ) { mySocket = s; Thread t = new Thread( this ); t.setDaemon( true ); t.start(); } public void run() { try { InputStream is = mySocket.getInputStream(); if ( is == null) return; // Read the first 8192 bytes. // The full header should fit in here. // Apache's default header limit is 8KB. int bufsize = 8192; byte[] buf = new byte[bufsize]; int rlen = is.read(buf, 0, bufsize); if (rlen <= 0) return; // Create a BufferedReader for parsing the header. ByteArrayInputStream hbis = new ByteArrayInputStream(buf, 0, rlen); BufferedReader hin = new BufferedReader( new InputStreamReader( hbis )); Properties pre = new Properties(); Properties parms = new Properties(); Properties header = new Properties(); Properties files = new Properties(); // Decode the header into parms and header java properties decodeHeader(hin, pre, parms, header); String method = pre.getProperty("method"); String uri = pre.getProperty("uri"); long size = 0x7FFFFFFFFFFFFFFFl; String contentLength = header.getProperty("content-length"); if (contentLength != null) { try { size = Integer.parseInt(contentLength); } catch (NumberFormatException ex) {} } // We are looking for the byte separating header from body. // It must be the last byte of the first two sequential new lines. int splitbyte = 0; boolean sbfound = false; while (splitbyte < rlen) { if (buf[splitbyte] == '\r' && buf[++splitbyte] == '\n' && buf[++splitbyte] == '\r' && buf[++splitbyte] == '\n') { sbfound = true; break; } splitbyte++; } splitbyte++; // Write the part of body already read to ByteArrayOutputStream f ByteArrayOutputStream f = new ByteArrayOutputStream(); if (splitbyte < rlen) f.write(buf, splitbyte, rlen-splitbyte); // While Firefox sends on the first read all the data fitting // our buffer, Chrome and Opera sends only the headers even if // there is data for the body. So we do some magic here to find // out whether we have already consumed part of body, if we // have reached the end of the data to be sent or we should // expect the first byte of the body at the next read. if (splitbyte < rlen) size -= rlen - splitbyte +1; else if (!sbfound || size == 0x7FFFFFFFFFFFFFFFl) size = 0; // Now read all the body and write it to f buf = new byte[512]; while ( rlen >= 0 && size > 0 ) { rlen = is.read(buf, 0, 512); size -= rlen; if (rlen > 0) f.write(buf, 0, rlen); } // Get the raw body as a byte [] byte [] fbuf = f.toByteArray(); // Create a BufferedReader for easily reading it as string. ByteArrayInputStream bin = new ByteArrayInputStream(fbuf); BufferedReader in = new BufferedReader( new InputStreamReader(bin)); // If the method is POST, there may be parameters // in data section, too, read it: if ( method.equalsIgnoreCase( "POST" )) { String contentType = ""; String contentTypeHeader = header.getProperty("content-type"); StringTokenizer st = new StringTokenizer( contentTypeHeader , "; " ); if ( st.hasMoreTokens()) { contentType = st.nextToken(); } if (contentType.equalsIgnoreCase("multipart/form-data")) { // Handle multipart/form-data if ( !st.hasMoreTokens()) sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html" ); String boundaryExp = st.nextToken(); st = new StringTokenizer( boundaryExp , "=" ); if (st.countTokens() != 2) sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary syntax error. Usage: GET /example/file.html" ); st.nextToken(); String boundary = st.nextToken(); decodeMultipartData(boundary, fbuf, in, parms, files); } else { // Handle application/x-www-form-urlencoded String postLine = ""; char pbuf[] = new char[512]; int read = in.read(pbuf); while ( read >= 0 && !postLine.endsWith("\r\n") ) { postLine += String.valueOf(pbuf, 0, read); read = in.read(pbuf); } postLine = postLine.trim(); decodeParms( postLine, parms ); } } // Ok, now do the serve() Response r = serve( uri, method, header, parms, files ); if ( r == null ) sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: Serve() returned a null response." ); else sendResponse( r.status, r.mimeType, r.header, r.data ); in.close(); is.close(); } catch ( IOException ioe ) { try { sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); } catch ( Throwable t ) {} } catch ( InterruptedException ie ) { // Thrown by sendError, ignore and exit the thread. } } /** * Decodes the sent headers and loads the data into * java Properties' key - value pairs **/ private void decodeHeader(BufferedReader in, Properties pre, Properties parms, Properties header) throws InterruptedException { try { // Read the request line String inLine = in.readLine(); if (inLine == null) return; StringTokenizer st = new StringTokenizer( inLine ); if ( !st.hasMoreTokens()) sendError( HTTP_BADREQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html" ); String method = st.nextToken(); pre.put("method", method); if ( !st.hasMoreTokens()) sendError( HTTP_BADREQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html" ); String uri = st.nextToken(); // Decode parameters from the URI int qmi = uri.indexOf( '?' ); if ( qmi >= 0 ) { decodeParms( uri.substring( qmi+1 ), parms ); uri = decodePercent( uri.substring( 0, qmi )); } else uri = decodePercent(uri); // If there's another token, it's protocol version, // followed by HTTP headers. Ignore version but parse headers. // NOTE: this now forces header names lowercase since they are // case insensitive and vary by client. if ( st.hasMoreTokens()) { String line = in.readLine(); while ( line != null && line.trim().length() > 0 ) { int p = line.indexOf( ':' ); if ( p >= 0 ) header.put( line.substring(0,p).trim().toLowerCase(), line.substring(p+1).trim()); line = in.readLine(); } } pre.put("uri", uri); } catch ( IOException ioe ) { sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); } } /** * Decodes the Multipart Body data and put it * into java Properties' key - value pairs. **/ private void decodeMultipartData(String boundary, byte[] fbuf, BufferedReader in, Properties parms, Properties files) throws InterruptedException { try { int[] bpositions = getBoundaryPositions(fbuf,boundary.getBytes()); int boundarycount = 1; String mpline = in.readLine(); while ( mpline != null ) { if (mpline.indexOf(boundary) == -1) sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html" ); boundarycount++; Properties item = new Properties(); mpline = in.readLine(); while (mpline != null && mpline.trim().length() > 0) { int p = mpline.indexOf( ':' ); if (p != -1) item.put( mpline.substring(0,p).trim().toLowerCase(), mpline.substring(p+1).trim()); mpline = in.readLine(); } if (mpline != null) { String contentDisposition = item.getProperty("content-disposition"); if (contentDisposition == null) { sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html" ); } StringTokenizer st = new StringTokenizer( contentDisposition , "; " ); Properties disposition = new Properties(); while ( st.hasMoreTokens()) { String token = st.nextToken(); int p = token.indexOf( '=' ); if (p!=-1) disposition.put( token.substring(0,p).trim().toLowerCase(), token.substring(p+1).trim()); } String pname = disposition.getProperty("name"); pname = pname.substring(1,pname.length()-1); String value = ""; if (item.getProperty("content-type") == null) { while (mpline != null && mpline.indexOf(boundary) == -1) { mpline = in.readLine(); if ( mpline != null) { int d = mpline.indexOf(boundary); if (d == -1) value+=mpline; else value+=mpline.substring(0,d-2); } } } else { if (boundarycount> bpositions.length) sendError( HTTP_INTERNALERROR, "Error processing request" ); int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount-2]); String path = saveTmpFile(fbuf, offset, bpositions[boundarycount-1]-offset-4); files.put(pname, path); value = disposition.getProperty("filename"); value = value.substring(1,value.length()-1); do { mpline = in.readLine(); } while (mpline != null && mpline.indexOf(boundary) == -1); } parms.put(pname, value); } } } catch ( IOException ioe ) { sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); } } /** * Find the byte positions where multipart boundaries start. **/ public int[] getBoundaryPositions(byte[] b, byte[] boundary) { int matchcount = 0; int matchbyte = -1; Vector matchbytes = new Vector(); for (int i=0; i<b.length; i++) { if (b[i] == boundary[matchcount]) { if (matchcount == 0) matchbyte = i; matchcount++; if (matchcount==boundary.length) { matchbytes.addElement(new Integer(matchbyte)); matchcount = 0; matchbyte = -1; } } else { i -= matchcount; matchcount = 0; matchbyte = -1; } } int[] ret = new int[matchbytes.size()]; for (int i=0; i < ret.length; i++) { ret[i] = ((Integer)matchbytes.elementAt(i)).intValue(); } return ret; } /** * Retrieves the content of a sent file and saves it * to a temporary file. * The full path to the saved file is returned. **/ private String saveTmpFile(byte[] b, int offset, int len) { String path = ""; if (len > 0) { String tmpdir = System.getProperty("java.io.tmpdir"); try { File temp = File.createTempFile("NanoHTTPD", "", new File(tmpdir)); OutputStream fstream = new FileOutputStream(temp); fstream.write(b, offset, len); fstream.close(); path = temp.getAbsolutePath(); } catch (Exception e) { // Catch exception if any System.err.println("Error: " + e.getMessage()); } } return path; } /** * It returns the offset separating multipart file headers * from the file's data. **/ private int stripMultipartHeaders(byte[] b, int offset) { int i = 0; for (i=offset; i<b.length; i++) { if (b[i] == '\r' && b[++i] == '\n' && b[++i] == '\r' && b[++i] == '\n') break; } return i+1; } /** * Decodes the percent encoding scheme. <br/> * For example: "an+example%20string" -> "an example string" */ private String decodePercent( String str ) throws InterruptedException { try { StringBuffer sb = new StringBuffer(); for( int i=0; i<str.length(); i++ ) { char c = str.charAt( i ); switch ( c ) { case '+': sb.append( ' ' ); break; case '%': sb.append((char)Integer.parseInt( str.substring(i+1,i+3), 16 )); i += 2; break; default: sb.append( c ); break; } } return sb.toString(); } catch( Exception e ) { sendError( HTTP_BADREQUEST, "BAD REQUEST: Bad percent-encoding." ); return null; } } /** * Decodes parameters in percent-encoded URI-format * ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and * adds them to given Properties. NOTE: this doesn't support multiple * identical keys due to the simplicity of Properties -- if you need multiples, * you might want to replace the Properties with a Hashtable of Vectors or such. */ private void decodeParms( String parms, Properties p ) throws InterruptedException { if ( parms == null ) return; StringTokenizer st = new StringTokenizer( parms, "&" ); while ( st.hasMoreTokens()) { String e = st.nextToken(); int sep = e.indexOf( '=' ); if ( sep >= 0 ) p.put( decodePercent( e.substring( 0, sep )).trim(), decodePercent( e.substring( sep+1 ))); } } /** * Returns an error message as a HTTP response and * throws InterruptedException to stop further request processing. */ private void sendError( String status, String msg ) throws InterruptedException { sendResponse( status, MIME_PLAINTEXT, null, new ByteArrayInputStream( msg.getBytes())); throw new InterruptedException(); } /** * Sends given response to the socket. */ private void sendResponse( String status, String mime, Properties header, InputStream data ) { try { if ( status == null ) throw new Error( "sendResponse(): Status can't be null." ); OutputStream out = mySocket.getOutputStream(); PrintWriter pw = new PrintWriter( out ); pw.print("HTTP/1.0 " + status + " \r\n"); if ( mime != null ) pw.print("Content-Type: " + mime + "\r\n"); if ( header == null || header.getProperty( "Date" ) == null ) pw.print( "Date: " + gmtFrmt.format( new Date()) + "\r\n"); if ( header != null ) { Enumeration e = header.keys(); while ( e.hasMoreElements()) { String key = (String)e.nextElement(); String value = header.getProperty( key ); pw.print( key + ": " + value + "\r\n"); } } pw.print("\r\n"); pw.flush(); if ( data != null ) { int pending = data.available(); // This is to support partial sends, see serveFile() byte[] buff = new byte[2048]; while (pending>0) { int read = data.read( buff, 0, ( (pending>2048) ? 2048 : pending )); if (read <= 0) break; out.write( buff, 0, read ); pending -= read; } } out.flush(); out.close(); if ( data != null ) data.close(); } catch( IOException ioe ) { // Couldn't write? No can do. try { mySocket.close(); } catch( Throwable t ) {} } } private Socket mySocket; } /** * URL-encodes everything between "/"-characters. * Encodes spaces as '%20' instead of '+'. */ private String encodeUri( String uri ) { String newUri = ""; StringTokenizer st = new StringTokenizer( uri, "/ ", true ); while ( st.hasMoreTokens()) { String tok = st.nextToken(); if ( tok.equals( "/" )) newUri += "/"; else if ( tok.equals( " " )) newUri += "%20"; else { newUri += URLEncoder.encode( tok ); // For Java 1.4 you'll want to use this instead: // try { newUri += URLEncoder.encode( tok, "UTF-8" ); } catch ( java.io.UnsupportedEncodingException uee ) {} } } return newUri; } private int myTcpPort; private final ServerSocket myServerSocket; private Thread myThread; private File myRootDir; // ================================================== // File server code // ================================================== /** * Serves file from homeDir and its' subdirectories (only). * Uses only URI, ignores all headers and HTTP parameters. */ public Response serveFile( String uri, Properties header, File homeDir, boolean allowDirectoryListing ) { Response res = null; // Make sure we won't die of an exception later if ( !homeDir.isDirectory()) res = new Response( HTTP_INTERNALERROR, MIME_PLAINTEXT, "INTERNAL ERRROR: serveFile(): given homeDir is not a directory." ); if ( res == null ) { // Remove URL arguments uri = uri.trim().replace( File.separatorChar, '/' ); if ( uri.indexOf( '?' ) >= 0 ) uri = uri.substring(0, uri.indexOf( '?' )); // Prohibit getting out of current directory if ( uri.startsWith( ".." ) || uri.endsWith( ".." ) || uri.indexOf( "../" ) >= 0 ) res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Won't serve ../ for security reasons." ); } File f = new File( homeDir, uri ); if ( res == null && !f.exists()) res = new Response( HTTP_NOTFOUND, MIME_PLAINTEXT, "Error 404, file not found." ); // List the directory, if necessary if ( res == null && f.isDirectory()) { // Browsers get confused without '/' after the // directory, send a redirect. if ( !uri.endsWith( "/" )) { uri += "/"; res = new Response( HTTP_REDIRECT, MIME_HTML, "<html><body>Redirected: <a href=\"" + uri + "\">" + uri + "</a></body></html>"); res.addHeader( "Location", uri ); } if ( res == null ) { // First try index.html and index.htm if ( new File( f, "index.html" ).exists()) f = new File( homeDir, uri + "/index.html" ); else if ( new File( f, "index.htm" ).exists()) f = new File( homeDir, uri + "/index.htm" ); // No index file, list the directory if it is readable else if ( allowDirectoryListing && f.canRead() ) { String[] files = f.list(); String msg = "<html><body><h1>Directory " + uri + "</h1><br/>"; if ( uri.length() > 1 ) { String u = uri.substring( 0, uri.length()-1 ); int slash = u.lastIndexOf( '/' ); if ( slash >= 0 && slash < u.length()) msg += "<b><a href=\"" + uri.substring(0, slash+1) + "\">..</a></b><br/>"; } if (files!=null) { for ( int i=0; i<files.length; ++i ) { File curFile = new File( f, files[i] ); boolean dir = curFile.isDirectory(); if ( dir ) { msg += "<b>"; files[i] += "/"; } msg += "<a href=\"" + encodeUri( uri + files[i] ) + "\">" + files[i] + "</a>"; // Show file size if ( curFile.isFile()) { long len = curFile.length(); msg += " &nbsp;<font size=2>("; if ( len < 1024 ) msg += len + " bytes"; else if ( len < 1024 * 1024 ) msg += len/1024 + "." + (len%1024/10%100) + " KB"; else msg += len/(1024*1024) + "." + len%(1024*1024)/10%100 + " MB"; msg += ")</font>"; } msg += "<br/>"; if ( dir ) msg += "</b>"; } } msg += "</body></html>"; res = new Response( HTTP_OK, MIME_HTML, msg ); } else { res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: No directory listing." ); } } } try { if ( res == null ) { // Get MIME type from file name extension, if possible String mime = null; int dot = f.getCanonicalPath().lastIndexOf( '.' ); if ( dot >= 0 ) mime = (String)theMimeTypes.get( f.getCanonicalPath().substring( dot + 1 ).toLowerCase()); if ( mime == null ) mime = MIME_DEFAULT_BINARY; // Support (simple) skipping: long startFrom = 0; long endAt = -1; String range = header.getProperty( "range" ); if ( range != null ) { if ( range.startsWith( "bytes=" )) { range = range.substring( "bytes=".length()); int minus = range.indexOf( '-' ); try { if ( minus > 0 ) { startFrom = Long.parseLong( range.substring( 0, minus )); endAt = Long.parseLong( range.substring( minus+1 )); } } catch ( NumberFormatException nfe ) {} } } // Change return code and add Content-Range header when skipping is requested long fileLen = f.length(); if (range != null && startFrom >= 0) { if ( startFrom >= fileLen) { res = new Response( HTTP_RANGE_NOT_SATISFIABLE, MIME_PLAINTEXT, "" ); res.addHeader( "Content-Range", "bytes 0-0/" + fileLen); } else { if ( endAt < 0 ) endAt = fileLen-1; long newLen = endAt - startFrom + 1; if ( newLen < 0 ) newLen = 0; final long dataLen = newLen; FileInputStream fis = new FileInputStream( f ) { public int available() throws IOException { return (int)dataLen; } }; fis.skip( startFrom ); res = new Response( HTTP_PARTIALCONTENT, mime, fis ); res.addHeader( "Content-Length", "" + dataLen); res.addHeader( "Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen); } } else { res = new Response( HTTP_OK, mime, new FileInputStream( f )); res.addHeader( "Content-Length", "" + fileLen); } } } catch( IOException ioe ) { res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed." ); } res.addHeader( "Accept-Ranges", "bytes"); // Announce that the file server accepts partial content requestes return res; } /** * Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE */ private static Hashtable theMimeTypes = new Hashtable(); static { StringTokenizer st = new StringTokenizer( "css text/css "+ "js text/javascript "+ "htm text/html "+ "html text/html "+ "txt text/plain "+ "asc text/plain "+ "gif image/gif "+ "jpg image/jpeg "+ "jpeg image/jpeg "+ "png image/png "+ "mp3 audio/mpeg "+ "m3u audio/mpeg-url " + "pdf application/pdf "+ "doc application/msword "+ "ogg application/x-ogg "+ "zip application/octet-stream "+ "exe application/octet-stream "+ "class application/octet-stream " ); while ( st.hasMoreTokens()) theMimeTypes.put( st.nextToken(), st.nextToken()); } /** * GMT date formatter */ private static java.text.SimpleDateFormat gmtFrmt; static { gmtFrmt = new java.text.SimpleDateFormat( "E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT")); } /** * The distribution licence */ private static final String LICENCE = "Copyright (C) 2001,2005-2011 by Jarno Elonen <elonen@iki.fi>\n"+ "and Copyright (C) 2010 by Konstantinos Togias <info@ktogias.gr>\n"+ "\n"+ "Redistribution and use in source and binary forms, with or without\n"+ "modification, are permitted provided that the following conditions\n"+ "are met:\n"+ "\n"+ "Redistributions of source code must retain the above copyright notice,\n"+ "this list of conditions and the following disclaimer. Redistributions in\n"+ "binary form must reproduce the above copyright notice, this list of\n"+ "conditions and the following disclaimer in the documentation and/or other\n"+ "materials provided with the distribution. The name of the author may not\n"+ "be used to endorse or promote products derived from this software without\n"+ "specific prior written permission. \n"+ " \n"+ "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"+ "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"+ "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"+ "IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"+ "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n"+ "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"+ "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"+ "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"+ "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"+ "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."; }
zzh84615-mycode
src/com/wireme/mediaserver/HttpServer.java
Java
asf20
29,704
package com.wireme.mediaserver; import org.teleal.cling.support.contentdirectory.AbstractContentDirectoryService; import org.teleal.cling.support.contentdirectory.ContentDirectoryErrorCode; import org.teleal.cling.support.contentdirectory.ContentDirectoryException; import org.teleal.cling.support.contentdirectory.DIDLParser; import org.teleal.cling.support.model.BrowseFlag; import org.teleal.cling.support.model.BrowseResult; import org.teleal.cling.support.model.DIDLContent; import org.teleal.cling.support.model.SortCriterion; import org.teleal.cling.support.model.container.Container; import org.teleal.cling.support.model.item.Item; import android.util.Log; public class ContentDirectoryService extends AbstractContentDirectoryService { private final static String LOGTAG = "MediaServer-CDS"; @Override public BrowseResult browse(String objectID, BrowseFlag browseFlag, String filter, long firstResult, long maxResults, SortCriterion[] orderby) throws ContentDirectoryException { // TODO Auto-generated method stub try { DIDLContent didl = new DIDLContent(); ContentNode contentNode = ContentTree.getNode(objectID); Log.v(LOGTAG, "someone's browsing id: " + objectID); if (contentNode == null) return new BrowseResult("", 0, 0); if (contentNode.isItem()) { didl.addItem(contentNode.getItem()); Log.v(LOGTAG, "returing item: " + contentNode.getItem().getTitle()); return new BrowseResult(new DIDLParser().generate(didl), 1, 1); } else { if (browseFlag == BrowseFlag.METADATA) { didl.addContainer(contentNode.getContainer()); Log.v(LOGTAG, "returning metadata of container: " + contentNode.getContainer().getTitle()); return new BrowseResult(new DIDLParser().generate(didl), 1, 1); } else { for (Container container : contentNode.getContainer() .getContainers()) { didl.addContainer(container); Log.v(LOGTAG, "getting child container: " + container.getTitle()); } for (Item item : contentNode.getContainer().getItems()) { didl.addItem(item); Log.v(LOGTAG, "getting child item: " + item.getTitle()); } return new BrowseResult(new DIDLParser().generate(didl), contentNode.getContainer().getChildCount(), contentNode.getContainer().getChildCount()); } } } catch (Exception ex) { throw new ContentDirectoryException( ContentDirectoryErrorCode.CANNOT_PROCESS, ex.toString()); } } @Override public BrowseResult search(String containerId, String searchCriteria, String filter, long firstResult, long maxResults, SortCriterion[] orderBy) throws ContentDirectoryException { // You can override this method to implement searching! return super.search(containerId, searchCriteria, filter, firstResult, maxResults, orderBy); } }
zzh84615-mycode
src/com/wireme/mediaserver/ContentDirectoryService.java
Java
asf20
2,858
package com.wireme.activity; import org.teleal.cling.model.meta.Device; import org.teleal.cling.model.meta.Service; import org.teleal.cling.support.model.DIDLObject; import org.teleal.cling.support.model.container.Container; import org.teleal.cling.support.model.item.Item; public class ContentItem { private Device device; private Service service; private DIDLObject content; private String id; private Boolean isContainer; public ContentItem(Container container, Service service) { // TODO Auto-generated constructor stub this.service = service; this.content = container; this.id = container.getId(); this.isContainer = true; } public ContentItem(Item item, Service service) { // TODO Auto-generated constructor stub this.service = service; this.content = item; this.id = item.getId(); this.isContainer = false; } public Container getContainer() { if(isContainer) return (Container) content; else { return null; } } public Item getItem() { if(isContainer) return null; else return (Item)content; } public Service getService() { return service; } public Boolean isContainer() { return isContainer; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ContentItem that = (ContentItem) o; if (!id.equals(that.id)) return false; return true; } @Override public int hashCode() { return content.hashCode(); } @Override public String toString() { return content.getTitle(); } }
zzh84615-mycode
src/com/wireme/activity/ContentItem.java
Java
asf20
1,630
package com.wireme.activity; import android.net.wifi.WifiManager; import org.teleal.cling.android.AndroidUpnpServiceConfiguration; import org.teleal.cling.android.AndroidUpnpServiceImpl; public class WireUpnpService extends AndroidUpnpServiceImpl { @Override protected AndroidUpnpServiceConfiguration createConfiguration( WifiManager wifiManager) { return new AndroidUpnpServiceConfiguration(wifiManager) { /* * The only purpose of this class is to show you how you'd configure * the AndroidUpnpServiceImpl in your application: * * @Override public int getRegistryMaintenanceIntervalMillis() { * return 7000; } * * @Override public ServiceType[] getExclusiveServiceTypes() { * return new ServiceType[] { new UDAServiceType("SwitchPower") }; } */ }; } }
zzh84615-mycode
src/com/wireme/activity/WireUpnpService.java
Java
asf20
807
/* * Copyright (C) 2010 Teleal GmbH, Switzerland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.wireme.activity; import org.teleal.cling.model.meta.Device; import org.teleal.cling.model.types.UDN; import android.graphics.drawable.Drawable; import android.view.Display; /** * Wraps a <tt>Device</tt> for display with icon and label. Equality is * implemented with UDN comparison. * */ public class DeviceItem { private UDN udn; private Device device; //TODO do we need label ? private String[] label; private Drawable icon; public DeviceItem(Device device) { this.udn = device.getIdentity().getUdn(); this.device = device; } public DeviceItem(Device device, String... label) { this.udn = device.getIdentity().getUdn(); this.device = device; this.label = label; } public UDN getUdn() { return udn; } public Device getDevice() { return device; } public String[] getLabel() { return label; } public void setLabel(String[] label) { this.label = label; } public Drawable getIcon() { return icon; } public void setIcon(Drawable icon) { this.icon = icon; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DeviceItem that = (DeviceItem) o; if (!udn.equals(that.udn)) return false; return true; } @Override public int hashCode() { return udn.hashCode(); } @Override public String toString() { String display; if (device.getDetails().getFriendlyName() != null) display = device.getDetails().getFriendlyName(); else display = device.getDisplayString(); // Display a little star while the device is being loaded (see // performance optimization earlier) return device.isFullyHydrated() ? display : display + " *"; } }
zzh84615-mycode
src/com/wireme/activity/DeviceItem.java
Java
asf20
2,445
package com.wireme.activity; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.logging.Level; import java.util.logging.Logger; import org.teleal.cling.android.AndroidUpnpService; import org.teleal.cling.model.meta.Device; import org.teleal.cling.model.meta.LocalDevice; import org.teleal.cling.model.meta.RemoteDevice; import org.teleal.cling.model.meta.Service; import org.teleal.cling.model.types.UDAServiceType; import org.teleal.cling.registry.DefaultRegistryListener; import org.teleal.cling.registry.Registry; import org.teleal.cling.support.contentdirectory.ui.ContentBrowseActionCallback; import org.teleal.cling.support.model.DIDLObject; import org.teleal.cling.support.model.PersonWithRole; import org.teleal.cling.support.model.Res; import org.teleal.cling.support.model.WriteStatus; import org.teleal.cling.support.model.container.Container; import org.teleal.cling.support.model.item.ImageItem; import org.teleal.cling.support.model.item.MusicTrack; import org.teleal.cling.support.model.item.VideoItem; import org.teleal.common.logging.LoggingUtil; import org.teleal.common.util.MimeType; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.database.Cursor; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.IBinder; import android.provider.MediaStore; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.wireme.R; import com.wireme.player.GPlayer; import com.wireme.mediaserver.ContentNode; import com.wireme.mediaserver.ContentTree; import com.wireme.mediaserver.MediaServer; import com.wireme.util.FixedAndroidHandler; public class MainActivity extends Activity { private static final Logger log = Logger.getLogger(MainActivity.class .getName()); private ListView deviceListView; private ListView contentListView; private ArrayAdapter<DeviceItem> deviceListAdapter; private ArrayAdapter<ContentItem> contentListAdapter; private AndroidUpnpService upnpService; private DeviceListRegistryListener deviceListRegistryListener; private MediaServer mediaServer; private static boolean serverPrepared = false; private final static String LOGTAG = "WireMe"; private ServiceConnection serviceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { upnpService = (AndroidUpnpService) service; Log.v(LOGTAG, "Connected to UPnP Service"); if (mediaServer == null) { try { mediaServer = new MediaServer(getLocalIpAddress()); upnpService.getRegistry() .addDevice(mediaServer.getDevice()); prepareMediaServer(); } catch (Exception ex) { // TODO: handle exception log.log(Level.SEVERE, "Creating demo device failed", ex); Toast.makeText(MainActivity.this, R.string.create_demo_failed, Toast.LENGTH_SHORT) .show(); return; } } deviceListAdapter.clear(); for (Device device : upnpService.getRegistry().getDevices()) { deviceListRegistryListener.deviceAdded(new DeviceItem(device)); } // Getting ready for future device advertisements upnpService.getRegistry().addListener(deviceListRegistryListener); // Refresh device list upnpService.getControlPoint().search(); } public void onServiceDisconnected(ComponentName className) { upnpService = null; } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Fix the logging integration between java.util.logging and Android // internal logging LoggingUtil.resetRootHandler(new FixedAndroidHandler()); Logger.getLogger("org.teleal.cling").setLevel(Level.INFO); /* * Enable this for debug logging: * * // UDP communication * Logger.getLogger("org.teleal.cling.transport.spi.DatagramIO" * ).setLevel(Level.FINE); * Logger.getLogger("org.teleal.cling.transport.spi.MulticastReceiver" * ).setLevel(Level.FINE); * * // Discovery * Logger.getLogger("org.teleal.cling.protocol.ProtocolFactory" * ).setLevel(Level.FINER); * Logger.getLogger("org.teleal.cling.protocol.async" * ).setLevel(Level.FINER); * * // Description * Logger.getLogger("org.teleal.cling.protocol.ProtocolFactory" * ).setLevel(Level.FINER); * Logger.getLogger("org.teleal.cling.protocol.RetrieveRemoteDescriptors" * ).setLevel(Level.FINE); * Logger.getLogger("org.teleal.cling.transport.spi.StreamClient" * ).setLevel(Level.FINEST); * * Logger.getLogger("org.teleal.cling.protocol.sync.ReceivingRetrieval"). * setLevel(Level.FINE); * Logger.getLogger("org.teleal.cling.binding.xml.DeviceDescriptorBinder" * ).setLevel(Level.FINE); * Logger.getLogger("org.teleal.cling.binding.xml.ServiceDescriptorBinder" * ).setLevel(Level.FINE); * Logger.getLogger("org.teleal.cling.transport.spi.SOAPActionProcessor" * ).setLevel(Level.FINEST); * * // Registry * Logger.getLogger("org.teleal.cling.registry.Registry").setLevel * (Level.FINER); * Logger.getLogger("org.teleal.cling.registry.LocalItems" * ).setLevel(Level.FINER); * Logger.getLogger("org.teleal.cling.registry.RemoteItems" * ).setLevel(Level.FINER); */ setContentView(R.layout.main); deviceListView = (ListView) findViewById(R.id.deviceList); contentListView = (ListView) findViewById(R.id.contentList); deviceListAdapter = new ArrayAdapter<DeviceItem>(this, android.R.layout.simple_list_item_1); deviceListRegistryListener = new DeviceListRegistryListener(); deviceListView.setAdapter(deviceListAdapter); deviceListView.setOnItemClickListener(deviceItemClickListener); contentListAdapter = new ArrayAdapter<ContentItem>(this, android.R.layout.simple_list_item_1); contentListView.setAdapter(contentListAdapter); contentListView.setOnItemClickListener(contentItemClickListener); getApplicationContext().bindService( new Intent(this, WireUpnpService.class), serviceConnection, Context.BIND_AUTO_CREATE); } @Override protected void onDestroy() { super.onDestroy(); if (upnpService != null) { upnpService.getRegistry() .removeListener(deviceListRegistryListener); } getApplicationContext().unbindService(serviceConnection); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, 0, 0, R.string.search_lan).setIcon( android.R.drawable.ic_menu_search); menu.add(0, 1, 0, R.string.toggle_debug_logging).setIcon( android.R.drawable.ic_menu_info_details); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 0: searchNetwork(); break; case 1: Logger logger = Logger.getLogger("org.teleal.cling"); if (logger.getLevel().equals(Level.FINEST)) { Toast.makeText(this, R.string.disabling_debug_logging, Toast.LENGTH_SHORT).show(); logger.setLevel(Level.INFO); } else { Toast.makeText(this, R.string.enabling_debug_logging, Toast.LENGTH_SHORT).show(); logger.setLevel(Level.FINEST); } break; } return false; } protected void searchNetwork() { if (upnpService == null) return; Toast.makeText(this, R.string.searching_lan, Toast.LENGTH_SHORT).show(); upnpService.getRegistry().removeAllRemoteDevices(); upnpService.getControlPoint().search(); } OnItemClickListener deviceItemClickListener = new OnItemClickListener() { protected Container createRootContainer(Service service) { Container rootContainer = new Container(); rootContainer.setId("0"); rootContainer.setTitle("Content Directory on " + service.getDevice().getDisplayString()); return rootContainer; } @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // TODO Auto-generated method stub Device device = deviceListAdapter.getItem(position).getDevice(); Service service = device.findService(new UDAServiceType( "ContentDirectory")); upnpService.getControlPoint().execute( new ContentBrowseActionCallback(MainActivity.this, service, createRootContainer(service), contentListAdapter)); } }; OnItemClickListener contentItemClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // TODO Auto-generated method stub ContentItem content = contentListAdapter.getItem(position); if (content.isContainer()) { upnpService.getControlPoint().execute( new ContentBrowseActionCallback(MainActivity.this, content.getService(), content.getContainer(), contentListAdapter)); } else { Intent intent = new Intent(); intent.setClass(MainActivity.this, GPlayer.class); intent.putExtra("playURI", content.getItem().getFirstResource() .getValue()); startActivity(intent); } } }; public class DeviceListRegistryListener extends DefaultRegistryListener { /* Discovery performance optimization for very slow Android devices! */ @Override public void remoteDeviceDiscoveryStarted(Registry registry, RemoteDevice device) { } @Override public void remoteDeviceDiscoveryFailed(Registry registry, final RemoteDevice device, final Exception ex) { } /* * End of optimization, you can remove the whole block if your Android * handset is fast (>= 600 Mhz) */ @Override public void remoteDeviceAdded(Registry registry, RemoteDevice device) { if (device.getType().getNamespace().equals("schemas-upnp-org") && device.getType().getType().equals("MediaServer")) { final DeviceItem display = new DeviceItem(device, device .getDetails().getFriendlyName(), device.getDisplayString(), "(REMOTE) " + device.getType().getDisplayString()); deviceAdded(display); } } @Override public void remoteDeviceRemoved(Registry registry, RemoteDevice device) { final DeviceItem display = new DeviceItem(device, device.getDisplayString()); deviceRemoved(display); } @Override public void localDeviceAdded(Registry registry, LocalDevice device) { final DeviceItem display = new DeviceItem(device, device .getDetails().getFriendlyName(), device.getDisplayString(), "(REMOTE) " + device.getType().getDisplayString()); deviceAdded(display); } @Override public void localDeviceRemoved(Registry registry, LocalDevice device) { final DeviceItem display = new DeviceItem(device, device.getDisplayString()); deviceRemoved(display); } public void deviceAdded(final DeviceItem di) { runOnUiThread(new Runnable() { public void run() { int position = deviceListAdapter.getPosition(di); if (position >= 0) { // Device already in the list, re-set new value at same // position deviceListAdapter.remove(di); deviceListAdapter.insert(di, position); } else { deviceListAdapter.add(di); } // Sort it? // listAdapter.sort(DISPLAY_COMPARATOR); // listAdapter.notifyDataSetChanged(); } }); } public void deviceRemoved(final DeviceItem di) { runOnUiThread(new Runnable() { public void run() { deviceListAdapter.remove(di); } }); } } private void prepareMediaServer() { if (serverPrepared) return; ContentNode rootNode = ContentTree.getRootNode(); // Video Container Container videoContainer = new Container(); videoContainer.setClazz(new DIDLObject.Class("object.container")); videoContainer.setId(ContentTree.VIDEO_ID); videoContainer.setParentID(ContentTree.ROOT_ID); videoContainer.setTitle("Videos"); videoContainer.setRestricted(true); videoContainer.setWriteStatus(WriteStatus.NOT_WRITABLE); videoContainer.setChildCount(0); rootNode.getContainer().addContainer(videoContainer); rootNode.getContainer().setChildCount( rootNode.getContainer().getChildCount() + 1); ContentTree.addNode(ContentTree.VIDEO_ID, new ContentNode( ContentTree.VIDEO_ID, videoContainer)); Cursor cursor; String[] videoColumns = { MediaStore.Video.Media._ID, MediaStore.Video.Media.TITLE, MediaStore.Video.Media.DATA, MediaStore.Video.Media.ARTIST, MediaStore.Video.Media.MIME_TYPE, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.DURATION, MediaStore.Video.Media.RESOLUTION }; cursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoColumns, null, null, null); if (cursor.moveToFirst()) { do { String id = ContentTree.VIDEO_PREFIX + cursor.getInt(cursor .getColumnIndex(MediaStore.Video.Media._ID)); String title = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.TITLE)); String creator = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.ARTIST)); String filePath = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.DATA)); String mimeType = cursor .getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE)); long size = cursor.getLong(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.SIZE)); long duration = cursor .getLong(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)); String resolution = cursor .getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.RESOLUTION)); Res res = new Res(new MimeType(mimeType.substring(0, mimeType.indexOf('/')), mimeType.substring(mimeType .indexOf('/') + 1)), size, "http://" + mediaServer.getAddress() + "/" + id); res.setDuration(duration / (1000 * 60 * 60) + ":" + (duration % (1000 * 60 * 60)) / (1000 * 60) + ":" + (duration % (1000 * 60)) / 1000); res.setResolution(resolution); VideoItem videoItem = new VideoItem(id, ContentTree.VIDEO_ID, title, creator, res); videoContainer.addItem(videoItem); videoContainer .setChildCount(videoContainer.getChildCount() + 1); ContentTree.addNode(id, new ContentNode(id, videoItem, filePath)); Log.v(LOGTAG, "added video item " + title + "from " + filePath); } while (cursor.moveToNext()); } // Audio Container Container audioContainer = new Container(ContentTree.AUDIO_ID, ContentTree.ROOT_ID, "Audios", "GNaP MediaServer", new DIDLObject.Class("object.container"), 0); audioContainer.setRestricted(true); audioContainer.setWriteStatus(WriteStatus.NOT_WRITABLE); rootNode.getContainer().addContainer(audioContainer); rootNode.getContainer().setChildCount( rootNode.getContainer().getChildCount() + 1); ContentTree.addNode(ContentTree.AUDIO_ID, new ContentNode( ContentTree.AUDIO_ID, audioContainer)); String[] audioColumns = { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.SIZE, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ALBUM }; cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, audioColumns, null, null, null); if (cursor.moveToFirst()) { do { String id = ContentTree.AUDIO_PREFIX + cursor.getInt(cursor .getColumnIndex(MediaStore.Audio.Media._ID)); String title = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)); String creator = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)); String filePath = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)); String mimeType = cursor .getString(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.MIME_TYPE)); long size = cursor.getLong(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE)); long duration = cursor .getLong(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)); String album = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)); Res res = new Res(new MimeType(mimeType.substring(0, mimeType.indexOf('/')), mimeType.substring(mimeType .indexOf('/') + 1)), size, "http://" + mediaServer.getAddress() + "/" + id); res.setDuration(duration / (1000 * 60 * 60) + ":" + (duration % (1000 * 60 * 60)) / (1000 * 60) + ":" + (duration % (1000 * 60)) / 1000); // Music Track must have `artist' with role field, or // DIDLParser().generate(didl) will throw nullpointException MusicTrack musicTrack = new MusicTrack(id, ContentTree.AUDIO_ID, title, creator, album, new PersonWithRole(creator, "Performer"), res); audioContainer.addItem(musicTrack); audioContainer .setChildCount(audioContainer.getChildCount() + 1); ContentTree.addNode(id, new ContentNode(id, musicTrack, filePath)); Log.v(LOGTAG, "added audio item " + title + "from " + filePath); } while (cursor.moveToNext()); } // Image Container Container imageContainer = new Container(ContentTree.IMAGE_ID, ContentTree.ROOT_ID, "Images", "GNaP MediaServer", new DIDLObject.Class("object.container"), 0); imageContainer.setRestricted(true); imageContainer.setWriteStatus(WriteStatus.NOT_WRITABLE); rootNode.getContainer().addContainer(imageContainer); rootNode.getContainer().setChildCount( rootNode.getContainer().getChildCount() + 1); ContentTree.addNode(ContentTree.IMAGE_ID, new ContentNode( ContentTree.IMAGE_ID, imageContainer)); String[] imageColumns = { MediaStore.Images.Media._ID, MediaStore.Images.Media.TITLE, MediaStore.Images.Media.DATA, MediaStore.Images.Media.MIME_TYPE, MediaStore.Images.Media.SIZE }; cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, null); if (cursor.moveToFirst()) { do { String id = ContentTree.IMAGE_PREFIX + cursor.getInt(cursor .getColumnIndex(MediaStore.Images.Media._ID)); String title = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Images.Media.TITLE)); String creator = "unkown"; String filePath = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); String mimeType = cursor .getString(cursor .getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE)); long size = cursor.getLong(cursor .getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)); Res res = new Res(new MimeType(mimeType.substring(0, mimeType.indexOf('/')), mimeType.substring(mimeType .indexOf('/') + 1)), size, "http://" + mediaServer.getAddress() + "/" + id); ImageItem imageItem = new ImageItem(id, ContentTree.IMAGE_ID, title, creator, res); imageContainer.addItem(imageItem); imageContainer .setChildCount(imageContainer.getChildCount() + 1); ContentTree.addNode(id, new ContentNode(id, imageItem, filePath)); Log.v(LOGTAG, "added image item " + title + "from " + filePath); } while (cursor.moveToNext()); } serverPrepared = true; } // FIXME: now only can get wifi address private InetAddress getLocalIpAddress() throws UnknownHostException { WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); return InetAddress.getByName(String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff))); } }
zzh84615-mycode
src/com/wireme/activity/MainActivity.java
Java
asf20
19,855
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class ViewCartAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CartActionForm cartForm = (CartActionForm) form; AccountActionForm acctForm = (AccountActionForm) request.getSession().getAttribute("accountForm"); String page = request.getParameter("page"); if (acctForm != null && acctForm.getAccount() != null) { if ("next".equals(page)) { acctForm.getMyList().nextPage(); } else if ("previous".equals(page)) { acctForm.getMyList().previousPage(); } } if ("nextCart".equals(page)) { cartForm.getCart().getCartItemList().nextPage(); } else if ("previousCart".equals(page)) { cartForm.getCart().getCartItemList().previousPage(); } return mapping.findForward("success"); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/ViewCartAction.java
Java
art
1,221
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.samples.jpetstore.domain.Account; public class NewOrderFormAction extends SecureBaseAction { protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AccountActionForm acctForm = (AccountActionForm) request.getSession().getAttribute("accountForm"); CartActionForm cartForm = (CartActionForm) request.getSession().getAttribute("cartForm"); if (cartForm != null) { OrderActionForm orderForm = (OrderActionForm) form; // Re-read account from DB at team's request. Account account = getPetStore().getAccount(acctForm.getAccount().getUsername()); orderForm.getOrder().initOrder(account, cartForm.getCart()); return mapping.findForward("success"); } else { request.setAttribute("message", "An order could not be created because a cart could not be found."); return mapping.findForward("failure"); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/NewOrderFormAction.java
Java
art
1,309
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class RemoveItemFromCartAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CartActionForm cartForm = (CartActionForm) form; cartForm.getCart().removeItemById(cartForm.getWorkingItemId()); return mapping.findForward("success"); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/RemoveItemFromCartAction.java
Java
art
687
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.samples.jpetstore.domain.Cart; import org.springframework.samples.jpetstore.domain.Item; public class AddItemToCartAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CartActionForm cartForm = (CartActionForm) form; Cart cart = cartForm.getCart(); String workingItemId = cartForm.getWorkingItemId(); if (cart.containsItemId(workingItemId)) { cart.incrementQuantityByItemId(workingItemId); } else { // isInStock is a "real-time" property that must be updated // every time an item is added to the cart, even if other // item details are cached. boolean isInStock = getPetStore().isItemInStock(workingItemId); Item item = getPetStore().getItem(workingItemId); cartForm.getCart().addItem(item, isInStock); } return mapping.findForward("success"); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/AddItemToCartAction.java
Java
art
1,301
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.samples.jpetstore.domain.Account; public class NewAccountFormAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AccountActionForm workingAcctForm = new AccountActionForm(); request.getSession().removeAttribute("workingAccountForm"); request.getSession().setAttribute("workingAccountForm", workingAcctForm); if (workingAcctForm.getAccount() == null) { workingAcctForm.setAccount(new Account()); } if (workingAcctForm.getCategories() == null) { workingAcctForm.setCategories(getPetStore().getCategoryList()); } return mapping.findForward("success"); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/NewAccountFormAction.java
Java
art
1,072
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.beans.support.PagedListHolder; import org.springframework.samples.jpetstore.domain.Account; public class EditAccountAction extends SecureBaseAction { protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AccountActionForm acctForm = (AccountActionForm) form; if (AccountActionForm.VALIDATE_EDIT_ACCOUNT.equals(acctForm.getValidate())) { acctForm.getAccount().setListOption(request.getParameter("account.listOption") != null); acctForm.getAccount().setBannerOption(request.getParameter("account.bannerOption") != null); Account account = acctForm.getAccount(); getPetStore().updateAccount(account); acctForm.setAccount(getPetStore().getAccount(account.getUsername())); PagedListHolder myList = new PagedListHolder(getPetStore().getProductListByCategory(account.getFavouriteCategoryId())); myList.setPageSize(4); acctForm.setMyList(myList); request.getSession().setAttribute("accountForm", acctForm); request.getSession().removeAttribute("workingAccountForm"); return mapping.findForward("success"); } else { request.setAttribute("message", "Your account was not updated because the submitted information was not validated."); return mapping.findForward("failure"); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/EditAccountAction.java
Java
art
1,680
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.ServletContext; import org.apache.struts.action.Action; import org.apache.struts.action.ActionServlet; import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; /** * Superclass for Struts actions in JPetStore's web tier. * * <p>Looks up the Spring WebApplicationContext via the ServletContext * and obtains the PetStoreFacade implementation from it, making it * available to subclasses via a protected getter method. * * <p>As alternative to such a base class, consider using Spring's * ActionSupport class for Struts, which pre-implements * WebApplicationContext lookup in a generic fashion. * * @author Juergen Hoeller * @since 30.11.2003 * @see #getPetStore * @see org.springframework.web.context.support.WebApplicationContextUtils#getRequiredWebApplicationContext * @see org.springframework.web.struts.ActionSupport */ public abstract class BaseAction extends Action { private PetStoreFacade petStore; public void setServlet(ActionServlet actionServlet) { super.setServlet(actionServlet); if (actionServlet != null) { ServletContext servletContext = actionServlet.getServletContext(); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); this.petStore = (PetStoreFacade) wac.getBean("petStore"); } } protected PetStoreFacade getPetStore() { return petStore; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/BaseAction.java
Java
art
1,644
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionMapping; import org.springframework.samples.jpetstore.domain.Cart; public class CartActionForm extends BaseActionForm { /* Private Fields */ private Cart cart = new Cart(); private String workingItemId; /* JavaBeans Properties */ public Cart getCart() { return cart; } public void setCart(Cart cart) { this.cart = cart; } public String getWorkingItemId() { return workingItemId; } public void setWorkingItemId(String workingItemId) { this.workingItemId = workingItemId; } /* Public Methods */ public void reset(ActionMapping mapping, HttpServletRequest request) { super.reset(mapping, request); workingItemId = null; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/CartActionForm.java
Java
art
834
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.samples.jpetstore.domain.Order; public class NewOrderAction extends SecureBaseAction { protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { OrderActionForm orderForm = (OrderActionForm) form; if (orderForm.isShippingAddressRequired()) { return mapping.findForward("shipping"); } else if (!orderForm.isConfirmed()) { return mapping.findForward("confirm"); } else if (orderForm.getOrder() != null) { Order order = orderForm.getOrder(); getPetStore().insertOrder(order); request.getSession().removeAttribute("workingOrderForm"); request.getSession().removeAttribute("cartForm"); request.setAttribute("order", order); request.setAttribute("message", "Thank you, your order has been submitted."); return mapping.findForward("success"); } else { request.setAttribute("message", "An error occurred processing your order (order was null)."); return mapping.findForward("failure"); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/NewOrderAction.java
Java
art
1,436
package org.springframework.samples.jpetstore.web.struts; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionMapping; import org.springframework.samples.jpetstore.domain.Order; public class OrderActionForm extends BaseActionForm { /* Constants */ private static final List CARD_TYPE_LIST = new ArrayList(); /* Private Fields */ private Order order; private boolean shippingAddressRequired; private boolean confirmed; private List cardTypeList; /* Static Initializer */ static { CARD_TYPE_LIST.add("Visa"); CARD_TYPE_LIST.add("MasterCard"); CARD_TYPE_LIST.add("American Express"); } /* Constructors */ public OrderActionForm() { this.order = new Order(); this.shippingAddressRequired = false; this.cardTypeList = CARD_TYPE_LIST; this.confirmed = false; } /* JavaBeans Properties */ public boolean isConfirmed() { return confirmed; } public void setConfirmed(boolean confirmed) { this.confirmed = confirmed; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } public boolean isShippingAddressRequired() { return shippingAddressRequired; } public void setShippingAddressRequired(boolean shippingAddressRequired) { this.shippingAddressRequired = shippingAddressRequired; } public List getCreditCardTypes() { return cardTypeList; } /* Public Methods */ public void doValidate(ActionMapping mapping, HttpServletRequest request, List errors) { if (!this.isShippingAddressRequired()) { addErrorIfStringEmpty(errors, "FAKE (!) credit card number required.", order.getCreditCard()); addErrorIfStringEmpty(errors, "Expiry date is required.", order.getExpiryDate()); addErrorIfStringEmpty(errors, "Card type is required.", order.getCardType()); addErrorIfStringEmpty(errors, "Shipping Info: first name is required.", order.getShipToFirstName()); addErrorIfStringEmpty(errors, "Shipping Info: last name is required.", order.getShipToLastName()); addErrorIfStringEmpty(errors, "Shipping Info: address is required.", order.getShipAddress1()); addErrorIfStringEmpty(errors, "Shipping Info: city is required.", order.getShipCity()); addErrorIfStringEmpty(errors, "Shipping Info: state is required.", order.getShipState()); addErrorIfStringEmpty(errors, "Shipping Info: zip/postal code is required.", order.getShipZip()); addErrorIfStringEmpty(errors, "Shipping Info: country is required.", order.getShipCountry()); addErrorIfStringEmpty(errors, "Billing Info: first name is required.", order.getBillToFirstName()); addErrorIfStringEmpty(errors, "Billing Info: last name is required.", order.getBillToLastName()); addErrorIfStringEmpty(errors, "Billing Info: address is required.", order.getBillAddress1()); addErrorIfStringEmpty(errors, "Billing Info: city is required.", order.getBillCity()); addErrorIfStringEmpty(errors, "Billing Info: state is required.", order.getBillState()); addErrorIfStringEmpty(errors, "Billing Info: zip/postal code is required.", order.getBillZip()); addErrorIfStringEmpty(errors, "Billing Info: country is required.", order.getBillCountry()); } if (errors.size() > 0) { order.setBillAddress1(order.getShipAddress1()); order.setBillAddress2(order.getShipAddress2()); order.setBillToFirstName(order.getShipToFirstName()); order.setBillToLastName(order.getShipToLastName()); order.setBillCity(order.getShipCity()); order.setBillCountry(order.getShipCountry()); order.setBillState(order.getShipState()); order.setBillZip(order.getShipZip()); } } public void reset(ActionMapping mapping, HttpServletRequest request) { super.reset(mapping, request); shippingAddressRequired = false; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/OrderActionForm.java
Java
art
4,008
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.samples.jpetstore.domain.Order; public class ViewOrderAction extends SecureBaseAction { protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AccountActionForm acctForm = (AccountActionForm) form; int orderId = Integer.parseInt(request.getParameter("orderId")); Order order = getPetStore().getOrder(orderId); if (acctForm.getAccount().getUsername().equals(order.getUsername())) { request.setAttribute("order", order); return mapping.findForward("success"); } else { request.setAttribute("message", "You may only view your own orders."); return mapping.findForward("failure"); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/ViewOrderAction.java
Java
art
1,083
package org.springframework.samples.jpetstore.web.struts; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; public class BaseActionForm extends ActionForm { /* Public Methods */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors actionErrors = null; ArrayList errorList = new ArrayList(); doValidate(mapping, request, errorList); request.setAttribute("errors", errorList); if (!errorList.isEmpty()) { actionErrors = new ActionErrors(); actionErrors.add(ActionErrors.GLOBAL_ERROR, new ActionError("global.error")); } return actionErrors; } public void doValidate(ActionMapping mapping, HttpServletRequest request, List errors) { } /* Protected Methods */ protected void addErrorIfStringEmpty(List errors, String message, String value) { if (value == null || value.trim().length() < 1) { errors.add(message); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/BaseActionForm.java
Java
art
1,206
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class ListOrdersAction extends SecureBaseAction { protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AccountActionForm acctForm = (AccountActionForm) form; String username = acctForm.getAccount().getUsername(); request.setAttribute("orderList", getPetStore().getOrdersByUsername(username)); return mapping.findForward("success"); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/ListOrdersAction.java
Java
art
774
package org.springframework.samples.jpetstore.web.struts; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.samples.jpetstore.domain.Account; public class EditAccountFormAction extends SecureBaseAction { protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AccountActionForm workingAcctForm = (AccountActionForm) form; AccountActionForm acctForm = (AccountActionForm) request.getSession().getAttribute("accountForm"); String username = acctForm.getAccount().getUsername(); if (workingAcctForm.getAccount() == null) { Account account = getPetStore().getAccount(username); workingAcctForm.setAccount(account); } if (workingAcctForm.getCategories() == null) { List categories = getPetStore().getCategoryList(); workingAcctForm.setCategories(categories); } return mapping.findForward("success"); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/EditAccountFormAction.java
Java
art
1,223
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.samples.jpetstore.domain.Item; public class ViewItemAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String itemId = request.getParameter("itemId"); Item item = getPetStore().getItem(itemId); request.setAttribute("item", item); request.setAttribute("product", item.getProduct()); return mapping.findForward("success"); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/ViewItemAction.java
Java
art
816
package org.springframework.samples.jpetstore.web.struts; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.samples.jpetstore.domain.CartItem; public class UpdateCartQuantitiesAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CartActionForm cartForm = (CartActionForm) form; Iterator cartItems = cartForm.getCart().getAllCartItems(); while (cartItems.hasNext()) { CartItem cartItem = (CartItem) cartItems.next(); String itemId = cartItem.getItem().getItemId(); try { int quantity = Integer.parseInt(request.getParameter(itemId)); cartForm.getCart().setQuantityByItemId(itemId, quantity); if (quantity < 1) { cartItems.remove(); } } catch (NumberFormatException e) { //ignore on purpose } } return mapping.findForward("success"); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/UpdateCartQuantitiesAction.java
Java
art
1,242
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class DoNothingAction extends BaseAction { /* Public Methods */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward("success"); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/DoNothingAction.java
Java
art
581
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.beans.support.PagedListHolder; import org.springframework.samples.jpetstore.domain.Category; public class ViewCategoryAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String categoryId = request.getParameter("categoryId"); if (categoryId != null) { Category category = getPetStore().getCategory(categoryId); PagedListHolder productList = new PagedListHolder(getPetStore().getProductListByCategory(categoryId)); productList.setPageSize(4); request.getSession().setAttribute("ViewProductAction_category", category); request.getSession().setAttribute("ViewProductAction_productList", productList); request.setAttribute("category", category); request.setAttribute("productList", productList); } else { Category category = (Category) request.getSession().getAttribute("ViewProductAction_category"); PagedListHolder productList = (PagedListHolder) request.getSession().getAttribute("ViewProductAction_productList"); if (category == null || productList == null) { throw new IllegalStateException("Cannot find pre-loaded category and product list"); } String page = request.getParameter("page"); if ("next".equals(page)) { productList.nextPage(); } else if ("previous".equals(page)) { productList.previousPage(); } request.setAttribute("category", category); request.setAttribute("productList", productList); } return mapping.findForward("success"); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/ViewCategoryAction.java
Java
art
1,953
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.beans.support.PagedListHolder; import org.springframework.samples.jpetstore.domain.Product; public class ViewProductAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String productId = request.getParameter("productId"); if (productId != null) { PagedListHolder itemList = new PagedListHolder(getPetStore().getItemListByProduct(productId)); itemList.setPageSize(4); Product product = getPetStore().getProduct(productId); request.getSession().setAttribute("ViewProductAction_itemList", itemList); request.getSession().setAttribute("ViewProductAction_product", product); request.setAttribute("itemList", itemList); request.setAttribute("product", product); } else { PagedListHolder itemList = (PagedListHolder) request.getSession().getAttribute("ViewProductAction_itemList"); Product product = (Product) request.getSession().getAttribute("ViewProductAction_product"); String page = request.getParameter("page"); if ("next".equals(page)) { itemList.nextPage(); } else if ("previous".equals(page)) { itemList.previousPage(); } request.setAttribute("itemList", itemList); request.setAttribute("product", product); } return mapping.findForward("success"); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/ViewProductAction.java
Java
art
1,752
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.beans.support.PagedListHolder; import org.springframework.util.StringUtils; public class SearchProductsAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String keyword = request.getParameter("keyword"); if (keyword != null) { if (!StringUtils.hasLength(keyword)) { request.setAttribute("message", "Please enter a keyword to search for, then press the search button."); return mapping.findForward("failure"); } PagedListHolder productList = new PagedListHolder(getPetStore().searchProductList(keyword.toLowerCase())); productList.setPageSize(4); request.getSession().setAttribute("SearchProductsAction_productList", productList); request.setAttribute("productList", productList); return mapping.findForward("success"); } else { String page = request.getParameter("page"); PagedListHolder productList = (PagedListHolder) request.getSession().getAttribute("SearchProductsAction_productList"); if (productList == null) { request.setAttribute("message", "Your session has timed out. Please start over again."); return mapping.findForward("failure"); } if ("next".equals(page)) { productList.nextPage(); } else if ("previous".equals(page)) { productList.previousPage(); } request.setAttribute("productList", productList); return mapping.findForward("success"); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/SearchProductsAction.java
Java
art
1,850
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.beans.support.PagedListHolder; import org.springframework.samples.jpetstore.domain.Account; public class SignonAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { request.getSession().removeAttribute("workingAccountForm"); request.getSession().removeAttribute("accountForm"); if (request.getParameter("signoff") != null) { request.getSession().invalidate(); return mapping.findForward("success"); } else { AccountActionForm acctForm = (AccountActionForm) form; String username = acctForm.getUsername(); String password = acctForm.getPassword(); Account account = getPetStore().getAccount(username, password); if (account == null) { request.setAttribute("message", "Invalid username or password. Signon failed."); return mapping.findForward("failure"); } else { String forwardAction = acctForm.getForwardAction(); acctForm = new AccountActionForm(); acctForm.setForwardAction(forwardAction); acctForm.setAccount(account); acctForm.getAccount().setPassword(null); PagedListHolder myList = new PagedListHolder(getPetStore().getProductListByCategory(account.getFavouriteCategoryId())); myList.setPageSize(4); acctForm.setMyList(myList); request.getSession().setAttribute("accountForm", acctForm); if (acctForm.getForwardAction() == null || acctForm.getForwardAction().length() < 1) { return mapping.findForward("success"); } else { response.sendRedirect(acctForm.getForwardAction()); return null; } } } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/SignonAction.java
Java
art
2,105
package org.springframework.samples.jpetstore.web.struts; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionMapping; import org.springframework.beans.support.PagedListHolder; import org.springframework.samples.jpetstore.domain.Account; public class AccountActionForm extends BaseActionForm { /* Constants */ public static final String VALIDATE_EDIT_ACCOUNT = "editAccount"; public static final String VALIDATE_NEW_ACCOUNT = "newAccount"; private static final ArrayList LANGUAGE_LIST = new ArrayList(); /* Private Fields */ private String username; private String password; private String repeatedPassword; private List languages; private List categories; private String validate; private String forwardAction; private Account account; private PagedListHolder myList; /* Static Initializer */ static { LANGUAGE_LIST.add("english"); LANGUAGE_LIST.add("japanese"); } /* Constructors */ public AccountActionForm() { languages = LANGUAGE_LIST; } /* JavaBeans Properties */ public PagedListHolder getMyList() { return myList; } public void setMyList(PagedListHolder myList) { this.myList = myList; } public String getForwardAction() { return forwardAction; } public void setForwardAction(String forwardAction) { this.forwardAction = forwardAction; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRepeatedPassword() { return repeatedPassword; } public void setRepeatedPassword(String repeatedPassword) { this.repeatedPassword = repeatedPassword; } public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } public List getLanguages() { return languages; } public void setLanguages(List languages) { this.languages = languages; } public List getCategories() { return categories; } public void setCategories(List categories) { this.categories = categories; } public String getValidate() { return validate; } public void setValidate(String validate) { this.validate = validate; } /* Public Methods */ public void doValidate(ActionMapping mapping, HttpServletRequest request, List errors) { if (validate != null) { if (VALIDATE_EDIT_ACCOUNT.equals(validate) || VALIDATE_NEW_ACCOUNT.equals(validate)) { if (VALIDATE_NEW_ACCOUNT.equals(validate)) { account.setStatus("OK"); addErrorIfStringEmpty(errors, "User ID is required.", account.getUsername()); if (account.getPassword() == null || account.getPassword().length() < 1 || !account.getPassword().equals(repeatedPassword)) { errors.add("Passwords did not match or were not provided. Matching passwords are required."); } } if (account.getPassword() != null && account.getPassword().length() > 0) { if (!account.getPassword().equals(repeatedPassword)) { errors.add("Passwords did not match."); } } addErrorIfStringEmpty(errors, "First name is required.", this.account.getFirstName()); addErrorIfStringEmpty(errors, "Last name is required.", this.account.getLastName()); addErrorIfStringEmpty(errors, "Email address is required.", this.account.getEmail()); addErrorIfStringEmpty(errors, "Phone number is required.", this.account.getPhone()); addErrorIfStringEmpty(errors, "Address (1) is required.", this.account.getAddress1()); addErrorIfStringEmpty(errors, "City is required.", this.account.getCity()); addErrorIfStringEmpty(errors, "State is required.", this.account.getState()); addErrorIfStringEmpty(errors, "ZIP is required.", this.account.getZip()); addErrorIfStringEmpty(errors, "Country is required.", this.account.getCountry()); } } } public void reset(ActionMapping mapping, HttpServletRequest request) { super.reset(mapping, request); setUsername(null); setPassword(null); setRepeatedPassword(null); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/AccountActionForm.java
Java
art
4,373
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.beans.support.PagedListHolder; import org.springframework.samples.jpetstore.domain.Account; public class NewAccountAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AccountActionForm acctForm = (AccountActionForm) form; if (AccountActionForm.VALIDATE_NEW_ACCOUNT.equals(acctForm.getValidate())) { acctForm.getAccount().setListOption(request.getParameter("account.listOption") != null); acctForm.getAccount().setBannerOption(request.getParameter("account.bannerOption") != null); Account account = acctForm.getAccount(); String username = acctForm.getAccount().getUsername(); getPetStore().insertAccount(account); acctForm.setAccount(getPetStore().getAccount(username)); PagedListHolder myList = new PagedListHolder(getPetStore().getProductListByCategory(account.getFavouriteCategoryId())); myList.setPageSize(4); acctForm.setMyList(myList); request.getSession().setAttribute("accountForm", acctForm); request.getSession().removeAttribute("workingAccountForm"); return mapping.findForward("success"); } else { request.setAttribute("message", "Your account was not created because the submitted information was not validated."); return mapping.findForward("failure"); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/NewAccountAction.java
Java
art
1,713
package org.springframework.samples.jpetstore.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public abstract class SecureBaseAction extends BaseAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AccountActionForm acctForm = (AccountActionForm) request.getSession().getAttribute("accountForm"); if (acctForm == null || acctForm.getAccount() == null) { String url = request.getServletPath(); String query = request.getQueryString(); if (query != null) { request.setAttribute("signonForwardAction", url+"?"+query); } else { request.setAttribute("signonForwardAction", url); } return mapping.findForward("global-signon"); } else { return doExecute(mapping, form, request, response); } } protected abstract ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception; }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/struts/SecureBaseAction.java
Java
art
1,266
package org.springframework.samples.jpetstore.web.spring; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.support.PagedListHolder; import org.springframework.samples.jpetstore.domain.Account; import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; /** * @author Juergen Hoeller * @since 30.11.2003 */ public class SignonController implements Controller { private PetStoreFacade petStore; public void setPetStore(PetStoreFacade petStore) { this.petStore = petStore; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String username = request.getParameter("username"); String password = request.getParameter("password"); Account account = this.petStore.getAccount(username, password); if (account == null) { return new ModelAndView("Error", "message", "Invalid username or password. Signon failed."); } else { UserSession userSession = new UserSession(account); PagedListHolder myList = new PagedListHolder(this.petStore.getProductListByCategory(account.getFavouriteCategoryId())); myList.setPageSize(4); userSession.setMyList(myList); request.getSession().setAttribute("userSession", userSession); String forwardAction = request.getParameter("forwardAction"); if (forwardAction != null) { response.sendRedirect(forwardAction); return null; } else { return new ModelAndView("index"); } } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/SignonController.java
Java
art
1,682
package org.springframework.samples.jpetstore.web.spring; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; /** * @author Juergen Hoeller * @since 30.11.2003 */ public class SignoffController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { request.getSession().removeAttribute("userSession"); request.getSession().invalidate(); return new ModelAndView("index"); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/SignoffController.java
Java
art
641
package org.springframework.samples.jpetstore.web.spring; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.samples.jpetstore.domain.Cart; import org.springframework.samples.jpetstore.domain.Item; import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.util.WebUtils; /** * @author Juergen Hoeller * @since 30.11.2003 */ public class AddItemToCartController implements Controller { private PetStoreFacade petStore; public void setPetStore(PetStoreFacade petStore) { this.petStore = petStore; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Cart cart = (Cart) WebUtils.getOrCreateSessionAttribute(request.getSession(), "sessionCart", Cart.class); String workingItemId = request.getParameter("workingItemId"); if (cart.containsItemId(workingItemId)) { cart.incrementQuantityByItemId(workingItemId); } else { // isInStock is a "real-time" property that must be updated // every time an item is added to the cart, even if other // item details are cached. boolean isInStock = this.petStore.isItemInStock(workingItemId); Item item = this.petStore.getItem(workingItemId); cart.addItem(item, isInStock); } return new ModelAndView("Cart", "cart", cart); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/AddItemToCartController.java
Java
art
1,536
package org.springframework.samples.jpetstore.web.spring; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.support.PagedListHolder; import org.springframework.samples.jpetstore.domain.Product; import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; /** * @author Juergen Hoeller * @since 30.11.2003 */ public class ViewProductController implements Controller { private PetStoreFacade petStore; public void setPetStore(PetStoreFacade petStore) { this.petStore = petStore; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Map model = new HashMap(); String productId = request.getParameter("productId"); if (productId != null) { PagedListHolder itemList = new PagedListHolder(this.petStore.getItemListByProduct(productId)); itemList.setPageSize(4); Product product = this.petStore.getProduct(productId); request.getSession().setAttribute("ViewProductAction_itemList", itemList); request.getSession().setAttribute("ViewProductAction_product", product); model.put("itemList", itemList); model.put("product", product); } else { PagedListHolder itemList = (PagedListHolder) request.getSession().getAttribute("ViewProductAction_itemList"); Product product = (Product) request.getSession().getAttribute("ViewProductAction_product"); String page = request.getParameter("page"); if ("next".equals(page)) { itemList.nextPage(); } else if ("previous".equals(page)) { itemList.previousPage(); } model.put("itemList", itemList); model.put("product", product); } return new ModelAndView("Product", model); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/ViewProductController.java
Java
art
1,952
package org.springframework.samples.jpetstore.web.spring; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.util.WebUtils; /** * @author Juergen Hoeller * @since 01.12.2003 */ public class ListOrdersController implements Controller { private PetStoreFacade petStore; public void setPetStore(PetStoreFacade petStore) { this.petStore = petStore; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { UserSession userSession = (UserSession) WebUtils.getRequiredSessionAttribute(request, "userSession"); String username = userSession.getAccount().getUsername(); Map model = new HashMap(); model.put("orderList", this.petStore.getOrdersByUsername(username)); return new ModelAndView("ListOrders", model); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/ListOrdersController.java
Java
art
1,129
package org.springframework.samples.jpetstore.web.spring; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.samples.jpetstore.domain.Order; import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.util.WebUtils; /** * @author Juergen Hoeller * @since 01.12.2003 */ public class ViewOrderController implements Controller { private PetStoreFacade petStore; public void setPetStore(PetStoreFacade petStore) { this.petStore = petStore; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { UserSession userSession = (UserSession) WebUtils.getRequiredSessionAttribute(request, "userSession"); int orderId = Integer.parseInt(request.getParameter("orderId")); Order order = this.petStore.getOrder(orderId); if (userSession.getAccount().getUsername().equals(order.getUsername())) { return new ModelAndView("ViewOrder", "order", order); } else { return new ModelAndView("Error", "message", "You may only view your own orders."); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/ViewOrderController.java
Java
art
1,284
package org.springframework.samples.jpetstore.web.spring; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.samples.jpetstore.domain.Cart; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.util.WebUtils; /** * @author Juergen Hoeller * @since 30.11.2003 */ public class ViewCartController implements Controller { private String successView; public void setSuccessView(String successView) { this.successView = successView; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession"); Cart cart = (Cart) WebUtils.getOrCreateSessionAttribute(request.getSession(), "sessionCart", Cart.class); String page = request.getParameter("page"); if (userSession != null) { if ("next".equals(page)) { userSession.getMyList().nextPage(); } else if ("previous".equals(page)) { userSession.getMyList().previousPage(); } } if ("nextCart".equals(page)) { cart.getCartItemList().nextPage(); } else if ("previousCart".equals(page)) { cart.getCartItemList().previousPage(); } return new ModelAndView(this.successView, "cart", cart); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/ViewCartController.java
Java
art
1,427
package org.springframework.samples.jpetstore.web.spring; import java.io.Serializable; import org.springframework.samples.jpetstore.domain.Order; /** * @author Juergen Hoeller * @since 01.12.2003 */ public class OrderForm implements Serializable { private final Order order = new Order(); private boolean shippingAddressRequired; private boolean confirmed; public Order getOrder() { return order; } public void setShippingAddressRequired(boolean shippingAddressRequired) { this.shippingAddressRequired = shippingAddressRequired; } public boolean isShippingAddressRequired() { return shippingAddressRequired; } public void setConfirmed(boolean confirmed) { this.confirmed = confirmed; } public boolean isConfirmed() { return confirmed; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/OrderForm.java
Java
art
816
package org.springframework.samples.jpetstore.web.spring; import java.io.Serializable; import org.springframework.beans.support.PagedListHolder; import org.springframework.samples.jpetstore.domain.Account; /** * @author Juergen Hoeller * @since 30.11.2003 */ public class UserSession implements Serializable { private Account account; private PagedListHolder myList; public UserSession(Account account) { this.account = account; } public Account getAccount() { return account; } public void setMyList(PagedListHolder myList) { this.myList = myList; } public PagedListHolder getMyList() { return myList; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/UserSession.java
Java
art
672
package org.springframework.samples.jpetstore.web.spring; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.support.PagedListHolder; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.samples.jpetstore.domain.Account; import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.validation.BindException; import org.springframework.validation.ValidationUtils; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import org.springframework.web.util.WebUtils; /** * @author Juergen Hoeller * @since 01.12.2003 */ public class AccountFormController extends SimpleFormController { public static final String[] LANGUAGES = {"english", "japanese"}; private PetStoreFacade petStore; public AccountFormController() { setSessionForm(true); setValidateOnBinding(false); setCommandName("accountForm"); setFormView("EditAccountForm"); } public void setPetStore(PetStoreFacade petStore) { this.petStore = petStore; } protected Object formBackingObject(HttpServletRequest request) throws Exception { UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession"); if (userSession != null) { return new AccountForm(this.petStore.getAccount(userSession.getAccount().getUsername())); } else { return new AccountForm(); } } protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception { AccountForm accountForm = (AccountForm) command; Account account = accountForm.getAccount(); if (request.getParameter("account.listOption") == null) { account.setListOption(false); } if (request.getParameter("account.bannerOption") == null) { account.setBannerOption(false); } errors.setNestedPath("account"); getValidator().validate(account, errors); errors.setNestedPath(""); if (accountForm.isNewAccount()) { account.setStatus("OK"); ValidationUtils.rejectIfEmpty(errors, "account.username", "USER_ID_REQUIRED", "User ID is required."); if (account.getPassword() == null || account.getPassword().length() < 1 || !account.getPassword().equals(accountForm.getRepeatedPassword())) { errors.reject("PASSWORD_MISMATCH", "Passwords did not match or were not provided. Matching passwords are required."); } } else if (account.getPassword() != null && account.getPassword().length() > 0) { if (!account.getPassword().equals(accountForm.getRepeatedPassword())) { errors.reject("PASSWORD_MISMATCH", "Passwords did not match. Matching passwords are required."); } } } protected Map referenceData(HttpServletRequest request) throws Exception { Map model = new HashMap(); model.put("languages", LANGUAGES); model.put("categories", this.petStore.getCategoryList()); return model; } protected ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { AccountForm accountForm = (AccountForm) command; try { if (accountForm.isNewAccount()) { this.petStore.insertAccount(accountForm.getAccount()); } else { this.petStore.updateAccount(accountForm.getAccount()); } } catch (DataIntegrityViolationException ex) { errors.rejectValue("account.username", "USER_ID_ALREADY_EXISTS", "User ID already exists: choose a different ID."); return showForm(request, response, errors); } UserSession userSession = new UserSession(this.petStore.getAccount(accountForm.getAccount().getUsername())); PagedListHolder myList = new PagedListHolder( this.petStore.getProductListByCategory(accountForm.getAccount().getFavouriteCategoryId())); myList.setPageSize(4); userSession.setMyList(myList); request.getSession().setAttribute("userSession", userSession); return super.onSubmit(request, response, command, errors); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/AccountFormController.java
Java
art
4,225
package org.springframework.samples.jpetstore.web.spring; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.support.PagedListHolder; import org.springframework.samples.jpetstore.domain.Category; import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; /** * @author Juergen Hoeller * @since 30.11.2003 */ public class ViewCategoryController implements Controller { private PetStoreFacade petStore; public void setPetStore(PetStoreFacade petStore) { this.petStore = petStore; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Map model = new HashMap(); String categoryId = request.getParameter("categoryId"); if (categoryId != null) { Category category = this.petStore.getCategory(categoryId); PagedListHolder productList = new PagedListHolder(this.petStore.getProductListByCategory(categoryId)); productList.setPageSize(4); request.getSession().setAttribute("ViewProductAction_category", category); request.getSession().setAttribute("ViewProductAction_productList", productList); model.put("category", category); model.put("productList", productList); } else { Category category = (Category) request.getSession().getAttribute("ViewProductAction_category"); PagedListHolder productList = (PagedListHolder) request.getSession().getAttribute("ViewProductAction_productList"); if (category == null || productList == null) { throw new IllegalStateException("Cannot find pre-loaded category and product list"); } String page = request.getParameter("page"); if ("next".equals(page)) { productList.nextPage(); } else if ("previous".equals(page)) { productList.previousPage(); } model.put("category", category); model.put("productList", productList); } return new ModelAndView("Category", model); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/ViewCategoryController.java
Java
art
2,160
package org.springframework.samples.jpetstore.web.spring; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.samples.jpetstore.domain.Item; import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; /** * @author Juergen Hoeller * @since 30.11.2003 */ public class ViewItemController implements Controller { private PetStoreFacade petStore; public void setPetStore(PetStoreFacade petStore) { this.petStore = petStore; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String itemId = request.getParameter("itemId"); Item item = this.petStore.getItem(itemId); Map model = new HashMap(); model.put("item", item); model.put("product", item.getProduct()); return new ModelAndView("Item", model); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/ViewItemController.java
Java
art
1,064
package org.springframework.samples.jpetstore.web.spring; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.support.PagedListHolder; import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.util.StringUtils; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; /** * @author Juergen Hoeller * @since 30.11.2003 */ public class SearchProductsController implements Controller { private PetStoreFacade petStore; public void setPetStore(PetStoreFacade petStore) { this.petStore = petStore; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String keyword = request.getParameter("keyword"); if (keyword != null) { if (!StringUtils.hasLength(keyword)) { return new ModelAndView("Error", "message", "Please enter a keyword to search for, then press the search button."); } PagedListHolder productList = new PagedListHolder(this.petStore.searchProductList(keyword.toLowerCase())); productList.setPageSize(4); request.getSession().setAttribute("SearchProductsController_productList", productList); return new ModelAndView("SearchProducts", "productList", productList); } else { String page = request.getParameter("page"); PagedListHolder productList = (PagedListHolder) request.getSession().getAttribute("SearchProductsController_productList"); if (productList == null) { return new ModelAndView("Error", "message", "Your session has timed out. Please start over again."); } if ("next".equals(page)) { productList.nextPage(); } else if ("previous".equals(page)) { productList.previousPage(); } return new ModelAndView("SearchProducts", "productList", productList); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/SearchProductsController.java
Java
art
1,939
package org.springframework.samples.jpetstore.web.spring; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.samples.jpetstore.domain.Account; import org.springframework.samples.jpetstore.domain.Cart; import org.springframework.samples.jpetstore.domain.logic.OrderValidator; import org.springframework.samples.jpetstore.domain.logic.PetStoreFacade; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndViewDefiningException; import org.springframework.web.servlet.mvc.AbstractWizardFormController; /** * @author Juergen Hoeller * @since 01.12.2003 */ public class OrderFormController extends AbstractWizardFormController { private PetStoreFacade petStore; public OrderFormController() { setCommandName("orderForm"); setPages(new String[] {"NewOrderForm", "ShippingForm", "ConfirmOrder"}); } public void setPetStore(PetStoreFacade petStore) { this.petStore = petStore; } protected Object formBackingObject(HttpServletRequest request) throws ModelAndViewDefiningException { UserSession userSession = (UserSession) request.getSession().getAttribute("userSession"); Cart cart = (Cart) request.getSession().getAttribute("sessionCart"); if (cart != null) { // Re-read account from DB at team's request. Account account = this.petStore.getAccount(userSession.getAccount().getUsername()); OrderForm orderForm = new OrderForm(); orderForm.getOrder().initOrder(account, cart); return orderForm; } else { ModelAndView modelAndView = new ModelAndView("Error"); modelAndView.addObject("message", "An order could not be created because a cart could not be found."); throw new ModelAndViewDefiningException(modelAndView); } } protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors, int page) { if (page == 0 && request.getParameter("shippingAddressRequired") == null) { OrderForm orderForm = (OrderForm) command; orderForm.setShippingAddressRequired(false); } } protected Map referenceData(HttpServletRequest request, int page) { if (page == 0) { List creditCardTypes = new ArrayList(); creditCardTypes.add("Visa"); creditCardTypes.add("MasterCard"); creditCardTypes.add("American Express"); Map model = new HashMap(); model.put("creditCardTypes", creditCardTypes); return model; } return null; } protected int getTargetPage(HttpServletRequest request, Object command, Errors errors, int currentPage) { OrderForm orderForm = (OrderForm) command; if (currentPage == 0 && orderForm.isShippingAddressRequired()) { return 1; } else { return 2; } } protected void validatePage(Object command, Errors errors, int page) { OrderForm orderForm = (OrderForm) command; OrderValidator orderValidator = (OrderValidator) getValidator(); errors.setNestedPath("order"); switch (page) { case 0: orderValidator.validateCreditCard(orderForm.getOrder(), errors); orderValidator.validateBillingAddress(orderForm.getOrder(), errors); break; case 1: orderValidator.validateShippingAddress(orderForm.getOrder(), errors); } errors.setNestedPath(""); } protected ModelAndView processFinish( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) { OrderForm orderForm = (OrderForm) command; this.petStore.insertOrder(orderForm.getOrder()); request.getSession().removeAttribute("sessionCart"); Map model = new HashMap(); model.put("order", orderForm.getOrder()); model.put("message", "Thank you, your order has been submitted."); return new ModelAndView("ViewOrder", model); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/OrderFormController.java
Java
art
4,026
package org.springframework.samples.jpetstore.web.spring; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.samples.jpetstore.domain.Cart; import org.springframework.samples.jpetstore.domain.CartItem; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.util.WebUtils; /** * @author Juergen Hoeller * @since 30.11.2003 */ public class UpdateCartQuantitiesController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Cart cart = (Cart) WebUtils.getOrCreateSessionAttribute(request.getSession(), "sessionCart", Cart.class); Iterator cartItems = cart.getAllCartItems(); while (cartItems.hasNext()) { CartItem cartItem = (CartItem) cartItems.next(); String itemId = cartItem.getItem().getItemId(); try { int quantity = Integer.parseInt(request.getParameter(itemId)); cart.setQuantityByItemId(itemId, quantity); if (quantity < 1) { cartItems.remove(); } } catch (NumberFormatException ex) { // ignore on purpose } } request.getSession().setAttribute("sessionCart", cart); return new ModelAndView("Cart", "cart", cart); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/UpdateCartQuantitiesController.java
Java
art
1,393
package org.springframework.samples.jpetstore.web.spring; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndViewDefiningException; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.util.WebUtils; /** * @author Juergen Hoeller * @since 01.12.2003 */ public class SignonInterceptor extends HandlerInterceptorAdapter { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession"); if (userSession == null) { String url = request.getServletPath(); String query = request.getQueryString(); ModelAndView modelAndView = new ModelAndView("SignonForm"); if (query != null) { modelAndView.addObject("signonForwardAction", url+"?"+query); } else { modelAndView.addObject("signonForwardAction", url); } throw new ModelAndViewDefiningException(modelAndView); } else { return true; } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/SignonInterceptor.java
Java
art
1,217
package org.springframework.samples.jpetstore.web.spring; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.samples.jpetstore.domain.Cart; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.util.WebUtils; /** * @author Juergen Hoeller * @since 30.11.2003 */ public class RemoveItemFromCartController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Cart cart = (Cart) WebUtils.getOrCreateSessionAttribute(request.getSession(), "sessionCart", Cart.class); cart.removeItemById(request.getParameter("workingItemId")); return new ModelAndView("Cart", "cart", cart); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/RemoveItemFromCartController.java
Java
art
849
package org.springframework.samples.jpetstore.web.spring; import java.io.Serializable; import org.springframework.samples.jpetstore.domain.Account; /** * @author Juergen Hoeller * @since 01.12.2003 */ public class AccountForm implements Serializable { private Account account; private boolean newAccount; private String repeatedPassword; public AccountForm(Account account) { this.account = account; this.newAccount = false; } public AccountForm() { this.account = new Account(); this.newAccount = true; } public Account getAccount() { return account; } public boolean isNewAccount() { return newAccount; } public void setRepeatedPassword(String repeatedPassword) { this.repeatedPassword = repeatedPassword; } public String getRepeatedPassword() { return repeatedPassword; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/web/spring/AccountForm.java
Java
art
869
package org.springframework.samples.jpetstore.service.client; import java.util.Iterator; import java.util.Map; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.springframework.samples.jpetstore.domain.LineItem; import org.springframework.samples.jpetstore.domain.Order; import org.springframework.samples.jpetstore.domain.logic.OrderService; import org.springframework.util.StopWatch; /** * Demo client class for remote OrderServices, to be invoked as standalone * program from the command line, e.g. via "client.bat" or "run.xml". * * <p>You need to specify an order ID and optionally a number of calls, * e.g. for order ID 1000: 'client 1000' for a single call per service or * 'client 1000 10' for 10 calls each". * * <p>Reads in the application context from a "clientContext.xml" file in * the VM execution directory, calling all OrderService proxies defined in it. * See that file for details. * * @author Juergen Hoeller * @since 26.12.2003 * @see org.springframework.samples.jpetstore.domain.logic.OrderService */ public class OrderServiceClient { public static final String CLIENT_CONTEXT_CONFIG_LOCATION = "clientContext.xml"; private final ListableBeanFactory beanFactory; public OrderServiceClient(ListableBeanFactory beanFactory) { this.beanFactory = beanFactory; } public void invokeOrderServices(int orderId, int nrOfCalls) { StopWatch stopWatch = new StopWatch(nrOfCalls + " OrderService call(s)"); Map orderServices = this.beanFactory.getBeansOfType(OrderService.class); for (Iterator it = orderServices.keySet().iterator(); it.hasNext();) { String beanName = (String) it.next(); OrderService orderService = (OrderService) orderServices.get(beanName); System.out.println("Calling OrderService '" + beanName + "' with order ID " + orderId); stopWatch.start(beanName); Order order = null; for (int i = 0; i < nrOfCalls; i++) { order = orderService.getOrder(orderId); } stopWatch.stop(); if (order != null) { printOrder(order); } else { System.out.println("Order with ID " + orderId + " not found"); } System.out.println(); } System.out.println(stopWatch.prettyPrint()); } protected void printOrder(Order order) { System.out.println("Got order with order ID " + order.getOrderId() + " and order date " + order.getOrderDate()); System.out.println("Shipping address is: " + order.getShipAddress1()); for (Iterator lineItems = order.getLineItems().iterator(); lineItems.hasNext();) { LineItem lineItem = (LineItem) lineItems.next(); System.out.println("LineItem " + lineItem.getLineNumber() + ": " + lineItem.getQuantity() + " piece(s) of item " + lineItem.getItemId()); } } public static void main(String[] args) { if (args.length == 0 || "".equals(args[0])) { System.out.println( "You need to specify an order ID and optionally a number of calls, e.g. for order ID 1000: " + "'client 1000' for a single call per service or 'client 1000 10' for 10 calls each"); } else { int orderId = Integer.parseInt(args[0]); int nrOfCalls = 1; if (args.length > 1 && !"".equals(args[1])) { nrOfCalls = Integer.parseInt(args[1]); } ListableBeanFactory beanFactory = new FileSystemXmlApplicationContext(CLIENT_CONTEXT_CONFIG_LOCATION); OrderServiceClient client = new OrderServiceClient(beanFactory); client.invokeOrderServices(orderId, nrOfCalls); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/service/client/OrderServiceClient.java
Java
art
3,614
package org.springframework.samples.jpetstore.service; import org.springframework.remoting.jaxrpc.ServletEndpointSupport; import org.springframework.samples.jpetstore.domain.Order; import org.springframework.samples.jpetstore.domain.logic.OrderService; /** * JAX-RPC OrderService endpoint that simply delegates to the OrderService * implementation in the root web application context. Implements the plain * OrderService interface as service interface, just like the target bean does. * * <p>This proxy class is necessary because JAX-RPC/Axis requires a dedicated * endpoint class to instantiate. If an existing service needs to be exported, * a wrapper that extends ServletEndpointSupport for simple application context * access is the simplest JAX-RPC compliant way. * * <p>This is the class registered with the server-side JAX-RPC implementation. * In the case of Axis, this happens in "server-config.wsdd" respectively via * deployment calls. The Web Service tool manages the lifecycle of instances * of this class: A Spring application context can just be accessed here. * * <p>Note that this class does <i>not</i> implement an RMI port interface, * despite the JAX-RPC spec requiring this for service endpoints. Axis and * other JAX-RPC implementations are known to accept non-RMI endpoint classes * too, so there's no need to maintain an RMI port interface in addition to * the existing non-RMI service interface (OrderService). * * <p>If your JAX-RPC implementation imposes a strict requirement on a service * endpoint class to implement an RMI port interface, then let your endpoint * class implement both the non-RMI service interface and the RMI port interface. * This will work as long as the methods in both interfaces just differ in the * declared RemoteException. Of course, this unfortunately involves double * maintenance: one interface for your business logic, one for JAX-RPC. * Therefore, it is usually preferable to avoid this if not absolutely necessary. * * @author Juergen Hoeller * @since 26.12.2003 */ public class JaxRpcOrderService extends ServletEndpointSupport implements OrderService { private OrderService orderService; protected void onInit() { this.orderService = (OrderService) getWebApplicationContext().getBean("petStore"); } public Order getOrder(int orderId) { return this.orderService.getOrder(orderId); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/service/JaxRpcOrderService.java
Java
art
2,445
package org.springframework.samples.jpetstore.domain; import java.io.Serializable; public class Category implements Serializable { /* Private Fields */ private String categoryId; private String name; private String description; /* JavaBeans Properties */ public String getCategoryId() { return categoryId; } public void setCategoryId(String categoryId) { this.categoryId = categoryId.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } /* Public Methods */ public String toString() { return getCategoryId(); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/Category.java
Java
art
779
package org.springframework.samples.jpetstore.domain; import java.io.Serializable; public class CartItem implements Serializable { /* Private Fields */ private Item item; private int quantity; private boolean inStock; /* JavaBeans Properties */ public boolean isInStock() { return inStock; } public void setInStock(boolean inStock) { this.inStock = inStock; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public double getTotalPrice() { if (item != null) { return item.getListPrice() * quantity; } else { return 0; } } /* Public methods */ public void incrementQuantity() { quantity++; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/CartItem.java
Java
art
866
package org.springframework.samples.jpetstore.domain; import java.io.Serializable; public class LineItem implements Serializable { /* Private Fields */ private int orderId; private int lineNumber; private int quantity; private String itemId; private double unitPrice; private Item item; /* Constructors */ public LineItem() { } public LineItem(int lineNumber, CartItem cartItem) { this.lineNumber = lineNumber; this.quantity = cartItem.getQuantity(); this.itemId = cartItem.getItem().getItemId(); this.unitPrice = cartItem.getItem().getListPrice(); this.item = cartItem.getItem(); } /* JavaBeans Properties */ public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public int getLineNumber() { return lineNumber; } public void setLineNumber(int lineNumber) { this.lineNumber = lineNumber; } public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public double getUnitPrice() { return unitPrice; } public void setUnitPrice(double unitprice) { this.unitPrice = unitprice; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public double getTotalPrice() { return this.unitPrice * this.quantity; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/LineItem.java
Java
art
1,518
package org.springframework.samples.jpetstore.domain; import java.io.Serializable; public class Product implements Serializable { /* Private Fields */ private String productId; private String categoryId; private String name; private String description; /* JavaBeans Properties */ public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId.trim(); } public String getCategoryId() { return categoryId; } public void setCategoryId(String categoryId) { this.categoryId = categoryId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } /* Public Methods*/ public String toString() { return getName(); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/Product.java
Java
art
934
package org.springframework.samples.jpetstore.domain; import java.io.Serializable; public class Item implements Serializable { /* Private Fields */ private String itemId; private String productId; private double listPrice; private double unitCost; private int supplierId; private String status; private String attribute1; private String attribute2; private String attribute3; private String attribute4; private String attribute5; private Product product; private int quantity; /* JavaBeans Properties */ public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId.trim(); } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public int getSupplierId() { return supplierId; } public void setSupplierId(int supplierId) { this.supplierId = supplierId; } public double getListPrice() { return listPrice; } public void setListPrice(double listPrice) { this.listPrice = listPrice; } public double getUnitCost() { return unitCost; } public void setUnitCost(double unitCost) { this.unitCost = unitCost; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getAttribute1() { return attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } public String getAttribute2() { return attribute2; } public void setAttribute2(String attribute2) { this.attribute2 = attribute2; } public String getAttribute3() { return attribute3; } public void setAttribute3(String attribute3) { this.attribute3 = attribute3; } public String getAttribute4() { return attribute4; } public void setAttribute4(String attribute4) { this.attribute4 = attribute4; } public String getAttribute5() { return attribute5; } public void setAttribute5(String attribute5) { this.attribute5 = attribute5; } /* Public Methods */ public String toString() { return "(" + getItemId().trim() + "-" + getProductId().trim() + ")"; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/Item.java
Java
art
2,421
package org.springframework.samples.jpetstore.domain; import java.io.Serializable; public class Account implements Serializable { /* Private Fields */ private String username; private String password; private String email; private String firstName; private String lastName; private String status; private String address1; private String address2; private String city; private String state; private String zip; private String country; private String phone; private String favouriteCategoryId; private String languagePreference; private boolean listOption; private boolean bannerOption; private String bannerName; /* JavaBeans Properties */ public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getAddress1() { return address1; } public void setAddress1(String address1) { this.address1 = address1; } public String getAddress2() { return address2; } public void setAddress2(String address2) { this.address2 = address2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getFavouriteCategoryId() { return favouriteCategoryId; } public void setFavouriteCategoryId(String favouriteCategoryId) { this.favouriteCategoryId = favouriteCategoryId; } public String getLanguagePreference() { return languagePreference; } public void setLanguagePreference(String languagePreference) { this.languagePreference = languagePreference; } public boolean isListOption() { return listOption; } public void setListOption(boolean listOption) { this.listOption = listOption; } public int getListOptionAsInt() { return listOption ? 1 : 0; } public boolean isBannerOption() { return bannerOption; } public void setBannerOption(boolean bannerOption) { this.bannerOption = bannerOption; } public int getBannerOptionAsInt() { return bannerOption ? 1 : 0; } public String getBannerName() { return bannerName; } public void setBannerName(String bannerName) { this.bannerName = bannerName; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/Account.java
Java
art
3,213
package org.springframework.samples.jpetstore.domain; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.springframework.beans.support.PagedListHolder; public class Cart implements Serializable { /* Private Fields */ private final Map itemMap = Collections.synchronizedMap(new HashMap()); private final PagedListHolder itemList = new PagedListHolder(); /* JavaBeans Properties */ public Cart() { this.itemList.setPageSize(4); } public Iterator getAllCartItems() { return itemList.getSource().iterator(); } public PagedListHolder getCartItemList() { return itemList; } public int getNumberOfItems() { return itemList.getSource().size(); } /* Public Methods */ public boolean containsItemId(String itemId) { return itemMap.containsKey(itemId); } public void addItem(Item item, boolean isInStock) { CartItem cartItem = (CartItem) itemMap.get(item.getItemId()); if (cartItem == null) { cartItem = new CartItem(); cartItem.setItem(item); cartItem.setQuantity(0); cartItem.setInStock(isInStock); itemMap.put(item.getItemId(), cartItem); itemList.getSource().add(cartItem); } cartItem.incrementQuantity(); } public Item removeItemById(String itemId) { CartItem cartItem = (CartItem) itemMap.remove(itemId); if (cartItem == null) { return null; } else { itemList.getSource().remove(cartItem); return cartItem.getItem(); } } public void incrementQuantityByItemId(String itemId) { CartItem cartItem = (CartItem) itemMap.get(itemId); cartItem.incrementQuantity(); } public void setQuantityByItemId(String itemId, int quantity) { CartItem cartItem = (CartItem) itemMap.get(itemId); cartItem.setQuantity(quantity); } public double getSubTotal() { double subTotal = 0; Iterator items = getAllCartItems(); while (items.hasNext()) { CartItem cartItem = (CartItem) items.next(); Item item = cartItem.getItem(); double listPrice = item.getListPrice(); int quantity = cartItem.getQuantity(); subTotal += listPrice * quantity; } return subTotal; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/Cart.java
Java
art
2,327
package org.springframework.samples.jpetstore.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; public class Order implements Serializable { /* Private Fields */ private int orderId; private String username; private Date orderDate; private String shipAddress1; private String shipAddress2; private String shipCity; private String shipState; private String shipZip; private String shipCountry; private String billAddress1; private String billAddress2; private String billCity; private String billState; private String billZip; private String billCountry; private String courier; private double totalPrice; private String billToFirstName; private String billToLastName; private String shipToFirstName; private String shipToLastName; private String creditCard; private String expiryDate; private String cardType; private String locale; private String status; private List lineItems = new ArrayList(); /* JavaBeans Properties */ public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getOrderDate() { return orderDate; } public void setOrderDate(Date orderDate) { this.orderDate = orderDate; } public String getShipAddress1() { return shipAddress1; } public void setShipAddress1(String shipAddress1) { this.shipAddress1 = shipAddress1; } public String getShipAddress2() { return shipAddress2; } public void setShipAddress2(String shipAddress2) { this.shipAddress2 = shipAddress2; } public String getShipCity() { return shipCity; } public void setShipCity(String shipCity) { this.shipCity = shipCity; } public String getShipState() { return shipState; } public void setShipState(String shipState) { this.shipState = shipState; } public String getShipZip() { return shipZip; } public void setShipZip(String shipZip) { this.shipZip = shipZip; } public String getShipCountry() { return shipCountry; } public void setShipCountry(String shipCountry) { this.shipCountry = shipCountry; } public String getBillAddress1() { return billAddress1; } public void setBillAddress1(String billAddress1) { this.billAddress1 = billAddress1; } public String getBillAddress2() { return billAddress2; } public void setBillAddress2(String billAddress2) { this.billAddress2 = billAddress2; } public String getBillCity() { return billCity; } public void setBillCity(String billCity) { this.billCity = billCity; } public String getBillState() { return billState; } public void setBillState(String billState) { this.billState = billState; } public String getBillZip() { return billZip; } public void setBillZip(String billZip) { this.billZip = billZip; } public String getBillCountry() { return billCountry; } public void setBillCountry(String billCountry) { this.billCountry = billCountry; } public String getCourier() { return courier; } public void setCourier(String courier) { this.courier = courier; } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } public String getBillToFirstName() { return billToFirstName; } public void setBillToFirstName(String billToFirstName) { this.billToFirstName = billToFirstName; } public String getBillToLastName() { return billToLastName; } public void setBillToLastName(String billToLastName) { this.billToLastName = billToLastName; } public String getShipToFirstName() { return shipToFirstName; } public void setShipToFirstName(String shipFoFirstName) { this.shipToFirstName = shipFoFirstName; } public String getShipToLastName() { return shipToLastName; } public void setShipToLastName(String shipToLastName) { this.shipToLastName = shipToLastName; } public String getCreditCard() { return creditCard; } public void setCreditCard(String creditCard) { this.creditCard = creditCard; } public String getExpiryDate() { return expiryDate; } public void setExpiryDate(String expiryDate) { this.expiryDate = expiryDate; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public void setLineItems(List lineItems) { this.lineItems = lineItems; } public List getLineItems() { return lineItems; } /* Public Methods */ public void initOrder(Account account, Cart cart) { username = account.getUsername(); orderDate = new Date(); shipToFirstName = account.getFirstName(); shipToLastName = account.getLastName(); shipAddress1 = account.getAddress1(); shipAddress2 = account.getAddress2(); shipCity = account.getCity(); shipState = account.getState(); shipZip = account.getZip(); shipCountry = account.getCountry(); billToFirstName = account.getFirstName(); billToLastName = account.getLastName(); billAddress1 = account.getAddress1(); billAddress2 = account.getAddress2(); billCity = account.getCity(); billState = account.getState(); billZip = account.getZip(); billCountry = account.getCountry(); totalPrice = cart.getSubTotal(); creditCard = "999 9999 9999 9999"; expiryDate = "12/03"; cardType = "Visa"; courier = "UPS"; locale = "CA"; status = "P"; Iterator i = cart.getAllCartItems(); while (i.hasNext()) { CartItem cartItem = (CartItem) i.next(); addLineItem(cartItem); } } public void addLineItem(CartItem cartItem) { LineItem lineItem = new LineItem(lineItems.size() + 1, cartItem); addLineItem(lineItem); } public void addLineItem(LineItem lineItem) { lineItems.add(lineItem); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/Order.java
Java
art
6,263
package org.springframework.samples.jpetstore.domain.logic; import java.util.List; import org.springframework.samples.jpetstore.dao.AccountDao; import org.springframework.samples.jpetstore.dao.CategoryDao; import org.springframework.samples.jpetstore.dao.ItemDao; import org.springframework.samples.jpetstore.dao.OrderDao; import org.springframework.samples.jpetstore.dao.ProductDao; import org.springframework.samples.jpetstore.domain.Account; import org.springframework.samples.jpetstore.domain.Category; import org.springframework.samples.jpetstore.domain.Item; import org.springframework.samples.jpetstore.domain.Order; import org.springframework.samples.jpetstore.domain.Product; /** * JPetStore's business layer facade. * * <p>This object makes use of five DAO objects, decoupling it from the * details of working with persistence APIs. Therefore, although this * application uses iBATIS for data access, a different persistence * strategy could be incorporated without breaking this class. * * <p>The DAOs are made available to the instance of this object * using Dependency Injection. (The DAOs are in turn configured * using Dependency Injection.) We use Setter Injection here, * exposing JavaBean setter methods for each DAO. This means there is * a JavaBean "property" for each DAO. In this case the properties * are write-only: there is no getter method to accompany the setter * methods. Getter methods are optional: implement them only if you * want to expose access to the properties in your business object. * * <p>There is one instance of this class in the JPetStore application. * In Spring terminology, it is a "singleton". This means a singleton * per Spring Application Context instance. The factory creates a * single instance; there is no need for a private constructor, * static factory method etc as in the traditional implementation * of the Singleton Design Pattern. * * <p>This is a POJO. It does not depend on any Spring APIs. * It is usable outside a Spring container, and can be instantiated * using new in a JUnit test. However, we can still apply declarative * transaction management to it using Spring AOP. * * <p>This class defines a default transaction attribute for all methods. * Note that this attribute definition is only necessary if using Commons * Attributes auto-proxying (see the "attributes" directory under the root of * JPetStore). No attributes are required with a TransactionFactoryProxyBean; * see the default <code>applicationContext.xml</code> config file in the * <code>war/WEB-INF</code> directory for an example. * * <p>The following attribute definition uses Commons Attributes attribute syntax. * @@org.springframework.transaction.interceptor.DefaultTransactionAttribute() * * @author Juergen Hoeller * @since 30.11.2003 */ public class PetStoreImpl implements PetStoreFacade, OrderService { private AccountDao accountDao; private CategoryDao categoryDao; private ProductDao productDao; private ItemDao itemDao; private OrderDao orderDao; //------------------------------------------------------------------------- // Setter methods for dependency injection //------------------------------------------------------------------------- public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } public void setCategoryDao(CategoryDao categoryDao) { this.categoryDao = categoryDao; } public void setProductDao(ProductDao productDao) { this.productDao = productDao; } public void setItemDao(ItemDao itemDao) { this.itemDao = itemDao; } public void setOrderDao(OrderDao orderDao) { this.orderDao = orderDao; } //------------------------------------------------------------------------- // Operation methods, implementing the PetStoreFacade interface //------------------------------------------------------------------------- public Account getAccount(String username) { return this.accountDao.getAccount(username); } public Account getAccount(String username, String password) { return this.accountDao.getAccount(username, password); } public void insertAccount(Account account) { this.accountDao.insertAccount(account); } public void updateAccount(Account account) { this.accountDao.updateAccount(account); } public List getUsernameList() { return this.accountDao.getUsernameList(); } public List getCategoryList() { return this.categoryDao.getCategoryList(); } public Category getCategory(String categoryId) { return this.categoryDao.getCategory(categoryId); } public List getProductListByCategory(String categoryId) { return this.productDao.getProductListByCategory(categoryId); } public List searchProductList(String keywords) { return this.productDao.searchProductList(keywords); } public Product getProduct(String productId) { return this.productDao.getProduct(productId); } public List getItemListByProduct(String productId) { return this.itemDao.getItemListByProduct(productId); } public Item getItem(String itemId) { return this.itemDao.getItem(itemId); } public boolean isItemInStock(String itemId) { return this.itemDao.isItemInStock(itemId); } public void insertOrder(Order order) { this.orderDao.insertOrder(order); this.itemDao.updateQuantity(order); } public Order getOrder(int orderId) { return this.orderDao.getOrder(orderId); } public List getOrdersByUsername(String username) { return this.orderDao.getOrdersByUsername(username); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/logic/PetStoreImpl.java
Java
art
5,668
package org.springframework.samples.jpetstore.domain.logic; import org.springframework.samples.jpetstore.domain.Account; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; /** * @author Juergen Hoeller * @since 01.12.2003 */ public class AccountValidator implements Validator { public boolean supports(Class clazz) { return Account.class.isAssignableFrom(clazz); } public void validate(Object obj, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "firstName", "FIRST_NAME_REQUIRED", "First name is required."); ValidationUtils.rejectIfEmpty(errors, "lastName", "LAST_NAME_REQUIRED", "Last name is required."); ValidationUtils.rejectIfEmpty(errors, "email", "EMAIL_REQUIRED", "Email address is required."); ValidationUtils.rejectIfEmpty(errors, "phone", "PHONE_REQUIRED", "Phone number is required."); ValidationUtils.rejectIfEmpty(errors, "address1", "ADDRESS_REQUIRED", "Address (1) is required."); ValidationUtils.rejectIfEmpty(errors, "city", "CITY_REQUIRED", "City is required."); ValidationUtils.rejectIfEmpty(errors, "state", "STATE_REQUIRED", "State is required."); ValidationUtils.rejectIfEmpty(errors, "zip", "ZIP_REQUIRED", "ZIP is required."); ValidationUtils.rejectIfEmpty(errors, "country", "COUNTRY_REQUIRED", "Country is required."); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/logic/AccountValidator.java
Java
art
1,418
package org.springframework.samples.jpetstore.domain.logic; import org.springframework.samples.jpetstore.domain.Order; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; /** * @author Juergen Hoeller * @since 01.12.2003 */ public class OrderValidator implements Validator { public boolean supports(Class clazz) { return Order.class.isAssignableFrom(clazz); } public void validate(Object obj, Errors errors) { validateCreditCard((Order) obj, errors); validateBillingAddress((Order) obj, errors); validateShippingAddress((Order) obj, errors); } public void validateCreditCard(Order order, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "creditCard", "CCN_REQUIRED", "FAKE (!) credit card number required."); ValidationUtils.rejectIfEmpty(errors, "expiryDate", "EXPIRY_DATE_REQUIRED", "Expiry date is required."); ValidationUtils.rejectIfEmpty(errors, "cardType", "CARD_TYPE_REQUIRED", "Card type is required."); } public void validateBillingAddress(Order order, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "billToFirstName", "FIRST_NAME_REQUIRED", "Billing Info: first name is required."); ValidationUtils.rejectIfEmpty(errors, "billToLastName", "LAST_NAME_REQUIRED", "Billing Info: last name is required."); ValidationUtils.rejectIfEmpty(errors, "billAddress1", "ADDRESS_REQUIRED", "Billing Info: address is required."); ValidationUtils.rejectIfEmpty(errors, "billCity", "CITY_REQUIRED", "Billing Info: city is required."); ValidationUtils.rejectIfEmpty(errors, "billState", "STATE_REQUIRED", "Billing Info: state is required."); ValidationUtils.rejectIfEmpty(errors, "billZip", "ZIP_REQUIRED", "Billing Info: zip/postal code is required."); ValidationUtils.rejectIfEmpty(errors, "billCountry", "COUNTRY_REQUIRED", "Billing Info: country is required."); } public void validateShippingAddress(Order order, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "shipToFirstName", "FIRST_NAME_REQUIRED", "Shipping Info: first name is required."); ValidationUtils.rejectIfEmpty(errors, "shipToLastName", "LAST_NAME_REQUIRED", "Shipping Info: last name is required."); ValidationUtils.rejectIfEmpty(errors, "shipAddress1", "ADDRESS_REQUIRED", "Shipping Info: address is required."); ValidationUtils.rejectIfEmpty(errors, "shipCity", "CITY_REQUIRED", "Shipping Info: city is required."); ValidationUtils.rejectIfEmpty(errors, "shipState", "STATE_REQUIRED", "Shipping Info: state is required."); ValidationUtils.rejectIfEmpty(errors, "shipZip", "ZIP_REQUIRED", "Shipping Info: zip/postal code is required."); ValidationUtils.rejectIfEmpty(errors, "shipCountry", "COUNTRY_REQUIRED", "Shipping Info: country is required."); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/logic/OrderValidator.java
Java
art
2,848
package org.springframework.samples.jpetstore.domain.logic; import java.util.List; import org.springframework.samples.jpetstore.domain.Account; import org.springframework.samples.jpetstore.domain.Category; import org.springframework.samples.jpetstore.domain.Item; import org.springframework.samples.jpetstore.domain.Order; import org.springframework.samples.jpetstore.domain.Product; /** * JPetStore's central business interface. * * @author Juergen Hoeller * @since 30.11.2003 */ public interface PetStoreFacade { Account getAccount(String username); Account getAccount(String username, String password); void insertAccount(Account account); void updateAccount(Account account); List getUsernameList(); List getCategoryList(); Category getCategory(String categoryId); List getProductListByCategory(String categoryId); List searchProductList(String keywords); Product getProduct(String productId); List getItemListByProduct(String productId); Item getItem(String itemId); boolean isItemInStock(String itemId); void insertOrder(Order order); Order getOrder(int orderId); List getOrdersByUsername(String username); }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/logic/PetStoreFacade.java
Java
art
1,216
package org.springframework.samples.jpetstore.domain.logic; import java.lang.reflect.Method; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.aop.AfterReturningAdvice; import org.springframework.beans.factory.InitializingBean; import org.springframework.mail.MailException; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage; import org.springframework.samples.jpetstore.domain.Account; import org.springframework.samples.jpetstore.domain.Order; /** * AOP advice that sends confirmation email after order has been submitted * @author Dmitriy Kopylenko */ public class SendOrderConfirmationEmailAdvice implements AfterReturningAdvice, InitializingBean { private static final String DEFAULT_MAIL_FROM = "jpetstore@springframework.org"; private static final String DEFAULT_SUBJECT = "Thank you for your order!"; private final Log logger = LogFactory.getLog(getClass()); private MailSender mailSender; private String mailFrom = DEFAULT_MAIL_FROM; private String subject = DEFAULT_SUBJECT; public void setMailSender(MailSender mailSender) { this.mailSender = mailSender; } public void setMailFrom(String mailFrom) { this.mailFrom = mailFrom; } public void setSubject(String subject) { this.subject = subject; } public void afterPropertiesSet() throws Exception { if (this.mailSender == null) { throw new IllegalStateException("mailSender is required"); } } public void afterReturning(Object returnValue, Method m, Object[] args, Object target) throws Throwable { Order order = (Order) args[0]; Account account = ((PetStoreFacade) target).getAccount(order.getUsername()); // don't do anything if email address is not set if (account.getEmail() == null || account.getEmail().length() == 0) { return; } StringBuffer text = new StringBuffer(); text.append("Dear ").append(account.getFirstName()).append(' ').append(account.getLastName()); text.append(", thank your for your order from JPetStore. Please note that your order number is "); text.append(order.getOrderId()); SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setTo(account.getEmail()); mailMessage.setFrom(this.mailFrom); mailMessage.setSubject(this.subject); mailMessage.setText(text.toString()); try { this.mailSender.send(mailMessage); } catch (MailException ex) { // just log it and go on logger.warn("An exception occured when trying to send email", ex); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/logic/SendOrderConfirmationEmailAdvice.java
Java
art
2,623
package org.springframework.samples.jpetstore.domain.logic; import org.springframework.samples.jpetstore.domain.Order; /** * Separate OrderService interface, implemented by PetStoreImpl * in addition to PetStoreFacade. * * <p>Mainly targeted at usage as remote service interface, * just exposing the <code>getOrder</code> method. * * @author Juergen Hoeller * @since 26.12.2003 * @see PetStoreFacade * @see PetStoreImpl * @see org.springframework.samples.jpetstore.service.JaxRpcOrderService */ public interface OrderService { Order getOrder(int orderId); }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/domain/logic/OrderService.java
Java
art
597
package org.springframework.samples.jpetstore.dao; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.samples.jpetstore.domain.Product; public interface ProductDao { List getProductListByCategory(String categoryId) throws DataAccessException; List searchProductList(String keywords) throws DataAccessException; Product getProduct(String productId) throws DataAccessException; }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/ProductDao.java
Java
art
457
package org.springframework.samples.jpetstore.dao.ibatis; import org.springframework.dao.DataAccessException; public class OracleSequenceDao extends SqlMapSequenceDao { /** * Get the next sequence using an Oracle thread-safe sequence * @param name Name is the name of the oracle sequence. * @return the next sequence */ public int getNextId(String name) throws DataAccessException { Sequence sequence = new Sequence(); sequence.setName(name); sequence = (Sequence) getSqlMapClientTemplate().queryForObject("oracleSequence", sequence); return sequence.getNextId(); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/ibatis/OracleSequenceDao.java
Java
art
625
package org.springframework.samples.jpetstore.dao.ibatis; import org.springframework.dao.DataAccessException; import org.springframework.samples.jpetstore.domain.LineItem; import org.springframework.samples.jpetstore.domain.Order; public class MsSqlOrderDao extends SqlMapOrderDao { /** * Special MS SQL Server version to allow the Item ID * to be retrieved from an identity column. */ public void insertOrder(Order order) throws DataAccessException { Integer orderId = (Integer) getSqlMapClientTemplate().queryForObject("msSqlServerInsertOrder", order); order.setOrderId(orderId.intValue()); getSqlMapClientTemplate().insert("insertOrderStatus", order); for (int i = 0; i < order.getLineItems().size(); i++) { LineItem lineItem = (LineItem) order.getLineItems().get(i); lineItem.setOrderId(order.getOrderId()); getSqlMapClientTemplate().insert("insertLineItem", lineItem); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/ibatis/MsSqlOrderDao.java
Java
art
962
package org.springframework.samples.jpetstore.dao.ibatis; import java.io.Serializable; public class Sequence implements Serializable { /* Private Fields */ private String name; private int nextId; /* Constructors */ public Sequence() { } public Sequence(String name, int nextId) { this.name = name; this.nextId = nextId; } /* JavaBeans Properties */ public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNextId() { return nextId; } public void setNextId(int nextId) { this.nextId = nextId; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/ibatis/Sequence.java
Java
art
625
package org.springframework.samples.jpetstore.dao.ibatis; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import org.springframework.samples.jpetstore.dao.CategoryDao; import org.springframework.samples.jpetstore.domain.Category; public class SqlMapCategoryDao extends SqlMapClientDaoSupport implements CategoryDao { public List getCategoryList() throws DataAccessException { return getSqlMapClientTemplate().queryForList("getCategoryList", null); } public Category getCategory(String categoryId) throws DataAccessException { return (Category) getSqlMapClientTemplate().queryForObject("getCategory", categoryId); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/ibatis/SqlMapCategoryDao.java
Java
art
756
package org.springframework.samples.jpetstore.dao.ibatis; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.dao.DataAccessException; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import org.springframework.samples.jpetstore.dao.ItemDao; import org.springframework.samples.jpetstore.domain.Item; import org.springframework.samples.jpetstore.domain.LineItem; import org.springframework.samples.jpetstore.domain.Order; public class SqlMapItemDao extends SqlMapClientDaoSupport implements ItemDao { public void updateQuantity(Order order) throws DataAccessException { for (int i = 0; i < order.getLineItems().size(); i++) { LineItem lineItem = (LineItem) order.getLineItems().get(i); String itemId = lineItem.getItemId(); Integer increment = new Integer(lineItem.getQuantity()); Map param = new HashMap(2); param.put("itemId", itemId); param.put("increment", increment); getSqlMapClientTemplate().update("updateInventoryQuantity", param, 1); } } public boolean isItemInStock(String itemId) throws DataAccessException { Integer i = (Integer) getSqlMapClientTemplate().queryForObject("getInventoryQuantity", itemId); return (i != null && i.intValue() > 0); } public List getItemListByProduct(String productId) throws DataAccessException { return getSqlMapClientTemplate().queryForList("getItemListByProduct", productId); } public Item getItem(String itemId) throws DataAccessException { Item item = (Item) getSqlMapClientTemplate().queryForObject("getItem", itemId); if (item != null) { Integer qty = (Integer) getSqlMapClientTemplate().queryForObject("getInventoryQuantity", itemId); item.setQuantity(qty.intValue()); } return item; } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/ibatis/SqlMapItemDao.java
Java
art
1,854
package org.springframework.samples.jpetstore.dao.ibatis; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import org.springframework.samples.jpetstore.dao.OrderDao; import org.springframework.samples.jpetstore.domain.LineItem; import org.springframework.samples.jpetstore.domain.Order; public class SqlMapOrderDao extends SqlMapClientDaoSupport implements OrderDao { private SqlMapSequenceDao sequenceDao; public void setSequenceDao(SqlMapSequenceDao sequenceDao) { this.sequenceDao = sequenceDao; } public List getOrdersByUsername(String username) throws DataAccessException { return getSqlMapClientTemplate().queryForList("getOrdersByUsername", username); } public Order getOrder(int orderId) throws DataAccessException { Object parameterObject = new Integer(orderId); Order order = (Order) getSqlMapClientTemplate().queryForObject("getOrder", parameterObject); if (order != null) { order.setLineItems(getSqlMapClientTemplate().queryForList("getLineItemsByOrderId", new Integer(order.getOrderId()))); } return order; } public void insertOrder(Order order) throws DataAccessException { order.setOrderId(this.sequenceDao.getNextId("ordernum")); getSqlMapClientTemplate().insert("insertOrder", order); getSqlMapClientTemplate().insert("insertOrderStatus", order); for (int i = 0; i < order.getLineItems().size(); i++) { LineItem lineItem = (LineItem) order.getLineItems().get(i); lineItem.setOrderId(order.getOrderId()); getSqlMapClientTemplate().insert("insertLineItem", lineItem); } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/ibatis/SqlMapOrderDao.java
Java
art
1,711
package org.springframework.samples.jpetstore.dao.ibatis; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import org.springframework.dao.DataAccessException; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import org.springframework.samples.jpetstore.dao.ProductDao; import org.springframework.samples.jpetstore.domain.Product; public class SqlMapProductDao extends SqlMapClientDaoSupport implements ProductDao { public List getProductListByCategory(String categoryId) throws DataAccessException { return getSqlMapClientTemplate().queryForList("getProductListByCategory", categoryId); } public Product getProduct(String productId) throws DataAccessException { return (Product) getSqlMapClientTemplate().queryForObject("getProduct", productId); } public List searchProductList(String keywords) throws DataAccessException { Object parameterObject = new ProductSearch(keywords); return getSqlMapClientTemplate().queryForList("searchProductList", parameterObject); } /* Inner Classes */ public static class ProductSearch { private List keywordList = new ArrayList(); public ProductSearch(String keywords) { StringTokenizer splitter = new StringTokenizer(keywords, " ", false); while (splitter.hasMoreTokens()) { this.keywordList.add("%" + splitter.nextToken() + "%"); } } public List getKeywordList() { return keywordList; } } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/ibatis/SqlMapProductDao.java
Java
art
1,529
package org.springframework.samples.jpetstore.dao.ibatis; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import org.springframework.samples.jpetstore.dao.AccountDao; import org.springframework.samples.jpetstore.domain.Account; /** * In this and other DAOs in this package, a DataSource property * is inherited from the SqlMapClientDaoSupport convenience superclass * supplied by Spring. DAOs don't need to extend such superclasses, * but it saves coding in many cases. There are analogous superclasses * for JDBC (JdbcDaoSupport), Hibernate (HibernateDaoSupport), * JDO (JdoDaoSupport) etc. * * <p>This and other DAOs are configured using Dependency Injection. * This means, for example, that Spring can source the DataSource * from a local class, such as the Commons DBCP BasicDataSource, * or from JNDI, concealing the JNDI lookup from application code. * * @author Juergen Hoeller * @author Colin Sampaleanu */ public class SqlMapAccountDao extends SqlMapClientDaoSupport implements AccountDao { public Account getAccount(String username) throws DataAccessException { return (Account) getSqlMapClientTemplate().queryForObject("getAccountByUsername", username); } public Account getAccount(String username, String password) throws DataAccessException { Account account = new Account(); account.setUsername(username); account.setPassword(password); return (Account) getSqlMapClientTemplate().queryForObject("getAccountByUsernameAndPassword", account); } public void insertAccount(Account account) throws DataAccessException { getSqlMapClientTemplate().insert("insertAccount", account); getSqlMapClientTemplate().insert("insertProfile", account); getSqlMapClientTemplate().insert("insertSignon", account); } public void updateAccount(Account account) throws DataAccessException { getSqlMapClientTemplate().update("updateAccount", account, 1); getSqlMapClientTemplate().update("updateProfile", account, 1); if (account.getPassword() != null && account.getPassword().length() > 0) { getSqlMapClientTemplate().update("updateSignon", account, 1); } } public List getUsernameList() throws DataAccessException { return getSqlMapClientTemplate().queryForList("getUsernameList", null); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/ibatis/SqlMapAccountDao.java
Java
art
2,437
package org.springframework.samples.jpetstore.dao.ibatis; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataRetrievalFailureException; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; public class SqlMapSequenceDao extends SqlMapClientDaoSupport { /** * This is a generic sequence ID generator that is based on a database * table called 'SEQUENCE', which contains two columns (NAME, NEXTID). * This approach should work with any database. * @param name the name of the sequence * @return the next ID */ public int getNextId(String name) throws DataAccessException { Sequence sequence = new Sequence(name, -1); sequence = (Sequence) getSqlMapClientTemplate().queryForObject("getSequence", sequence); if (sequence == null) { throw new DataRetrievalFailureException( "Could not get next value of sequence '" + name + "': sequence does not exist"); } Object parameterObject = new Sequence(name, sequence.getNextId() + 1); getSqlMapClientTemplate().update("updateSequence", parameterObject, 1); return sequence.getNextId(); } }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/ibatis/SqlMapSequenceDao.java
Java
art
1,176
package org.springframework.samples.jpetstore.dao; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.samples.jpetstore.domain.Category; public interface CategoryDao { List getCategoryList() throws DataAccessException; Category getCategory(String categoryId) throws DataAccessException; }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/CategoryDao.java
Java
art
363
package org.springframework.samples.jpetstore.dao; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.samples.jpetstore.domain.Order; public interface OrderDao { List getOrdersByUsername(String username) throws DataAccessException; Order getOrder(int orderId) throws DataAccessException; void insertOrder(Order order) throws DataAccessException; }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/OrderDao.java
Java
art
428
package org.springframework.samples.jpetstore.dao; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.samples.jpetstore.domain.Item; import org.springframework.samples.jpetstore.domain.Order; public interface ItemDao { public void updateQuantity(Order order) throws DataAccessException; boolean isItemInStock(String itemId) throws DataAccessException; List getItemListByProduct(String productId) throws DataAccessException; Item getItem(String itemId) throws DataAccessException; }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/ItemDao.java
Java
art
568
package org.springframework.samples.jpetstore.dao; import java.util.List; import org.springframework.dao.DataAccessException; import org.springframework.samples.jpetstore.domain.Account; public interface AccountDao { Account getAccount(String username) throws DataAccessException; Account getAccount(String username, String password) throws DataAccessException; void insertAccount(Account account) throws DataAccessException; void updateAccount(Account account) throws DataAccessException; List getUsernameList() throws DataAccessException; }
zzh-simple-hr
Zjpetstore/src/org/springframework/samples/jpetstore/dao/AccountDao.java
Java
art
581
<HTML><HEAD><TITLE>JPetStore Demo</TITLE> <META content="text/html; charset=windows-1252" http-equiv=Content-Type> </HEAD> <BODY bgColor=white> <TABLE background="images/bkg-topbar.gif" border=0 cellSpacing=0 cellPadding=5 width="100%"> <TBODY> <TR> <TD><A href="shop/index.do"><IMG border=0 src="images/logo-topbar.gif"></A> </TD> <TD align=right><A href="shop/viewCart.do"><IMG border=0 name=img_cart src="images/cart.gif"></A> <IMG border=0 src="images/separator.gif"> <A href="shop/signonForm.do" > <IMG border=0 name=img_signin src="images/sign-in.gif"></A> <IMG border=0 src="images/separator.gif"> <A href="help.html" ><IMG border=0 name=img_help src="images/help.gif"></A> </TD> <TD align=left valign=bottom> <FORM action="shop/searchProducts.do"> <INPUT name=keyword size=14> <INPUT border=0 src="images/search.gif" type=image> </FORM> </TD> </TR> </TBODY></TABLE> <TABLE border=0 cellSpacing=0 width="100%"> <TBODY> <TR> <TD vAlign=top width=100%> <p>&nbsp;</p> <p align="center"><b>Welcome to the Spring JPetStore, by Juergen Hoeller</b></p> <p align="center">Based on the iBATIS JPetStore, by Clinton Begin</p> <p align="center"> <i> This application demonstrates the use of Spring for the middle tier, including declarative transaction management applied to POJO business objects. This application can easily be configured to use JTA or JDBC for transaction management, so it allows declarative transaction management in a web container without JTA. <br><br>There are alternative Spring and Struts MVC layers built on a shared Spring middle tier. </i> </p> <p align="center"><a href="shop/index.do">Enter the Store</a></p> </TD> </TR> </TBODY> </TABLE> <p>&nbsp;</p> <table align="center"> <tr> <td> <a href="http://www.springframework.org"> <img border="0" align="center" src="images/poweredBySpring.gif" alt="Powered by the Spring Framework"/> </a> </td> <td> <a href="http://www.ibatis.com"> <img border="0" align="center" src="images/poweredby.gif" alt="Powered by iBATIS"/> </a> </td> </tr> </table> </BODY> </HTML>
zzh-simple-hr
Zjpetstore/webapp/index.html
HTML
art
2,380
<%@ include file="IncludeTop.jsp" %> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr><td valign="top" width="20%" align="left"> <table align="left" bgcolor="#008800" border="0" cellspacing="2" cellpadding="2"> <tr><td bgcolor="#FFFF88"> <a href="<c:url value="/shop/index.do"/>"><b><font color="BLACK" size="2">&lt;&lt; Main Menu</font></b></a> </td></tr> </table> </td><td valign="top" align="center"> <h2 align="center">Shopping Cart</h2> <form action="<c:url value="/shop/updateCartQuantities.do"/>" method="post"> <table align="center" bgcolor="#008800" border="0" cellspacing="2" cellpadding="5"> <tr bgcolor="#cccccc"> <td><b>Item ID</b></td> <td><b>Product ID</b></td> <td><b>Description</b></td> <td><b>In Stock?</b></td> <td><b>Quantity</b></td> <td><b>List Price</b></td> <td><b>Total Cost</b></td> <td>&nbsp;</td> </tr> <c:if test="${cartForm.cart.numberOfItems == 0}"> <tr bgcolor="#FFFF88"><td colspan="8"><b>Your cart is empty.</b></td></tr> </c:if> <c:forEach var="cartItem" items="${cartForm.cart.cartItemList.pageList}"> <tr bgcolor="#FFFF88"> <td><b> <a href="<c:url value="/shop/viewItem.do"><c:param name="itemId" value="${cartItem.item.itemId}"/></c:url>"> <c:out value="${cartItem.item.itemId}"/> </a></b></td> <td><c:out value="${cartItem.item.productId}"/></td> <td> <c:out value="${cartItem.item.attribute1}"/> <c:out value="${cartItem.item.attribute2}"/> <c:out value="${cartItem.item.attribute3}"/> <c:out value="${cartItem.item.attribute4}"/> <c:out value="${cartItem.item.attribute5}"/> <c:out value="${cartItem.item.product.name}"/> </td> <td align="center"><c:out value="${cartItem.inStock}"/></td> <td align="center"> <input type="text" size="3" name="<c:out value="${cartItem.item.itemId}"/>" value="<c:out value="${cartItem.quantity}"/>" /> </td> <td align="right"><fmt:formatNumber value="${cartItem.item.listPrice}" pattern="$#,##0.00" /></td> <td align="right"><fmt:formatNumber value="${cartItem.totalPrice}" pattern="$#,##0.00" /></td> <td><a href="<c:url value="/shop/removeItemFromCart.do"><c:param name="workingItemId" value="${cartItem.item.itemId}"/></c:url>"> <img border="0" src="../images/button_remove.gif" /> </a></td> </tr> </c:forEach> <tr bgcolor="#FFFF88"> <td colspan="7" align="right"> <b>Sub Total: <fmt:formatNumber value="${cartForm.cart.subTotal}" pattern="$#,##0.00" /></b><br/> <input type="image" border="0" src="../images/button_update_cart.gif" name="update" /> </td> <td>&nbsp;</td> </tr> </table> <center> <c:if test="${!cartForm.cart.cartItemList.firstPage}"> <a href="<c:url value="viewCart.do?page=previousCart"/>"><font color="green"><B>&lt;&lt; Prev</B></font></a> </c:if> <c:if test="${!cartForm.cart.cartItemList.lastPage}"> <a href="<c:url value="viewCart.do?page=nextCart"/>"><font color="green"><B>Next &gt;&gt;</B></font></a> </c:if> </center> </form> <c:if test="${cartForm.cart.numberOfItems > 0}"> <br /><center><a href="<c:url value="/shop/checkout.do"/>"><img border="0" src="../images/button_checkout.gif" /></a></center> </c:if> </td> <td valign="top" width="20%" align="right"> <c:if test="${!empty accountForm.account.username}"> <c:if test="${accountForm.account.listOption}"> <%@ include file="IncludeMyList.jsp" %> </c:if> </c:if> </td> </tr> </table> <%@ include file="IncludeBanner.jsp" %> <%@ include file="IncludeBottom.jsp" %>
zzh-simple-hr
Zjpetstore/webapp/WEB-INF/jsp/struts/Cart.jsp
Java Server Pages
art
3,534
<%@ include file="IncludeTop.jsp" %> <table border="0" cellspacing="0" width="100%"> <tbody> <tr> <td valign="top" width="100%"> <table align="left" border="0" cellspacing="0" width="80%"> <tbody> <tr> <td valign="top"> <!-- SIDEBAR --> <table bgcolor="#FFFF88" border="0" cellspacing="0" cellpadding="5" width="200"> <tbody> <tr> <td> <c:if test="${!empty accountForm.account}"> <b><i><font size="2" color="BLACK">Welcome <c:out value="${accountForm.account.firstName}"/>!</font></i></b> </c:if> &nbsp; </td> </tr> <tr> <td> <a href="<c:url value="/shop/viewCategory.do?categoryId=FISH"/>"> <img border="0" src="../images/fish_icon.gif" /></a> </td> </tr> <tr> <td> <a href="<c:url value="/shop/viewCategory.do?categoryId=DOGS"/>"> <img border="0" src="../images/dogs_icon.gif" /></a> </td> </tr> <tr> <td> <a href="<c:url value="/shop/viewCategory.do?categoryId=CATS"/>"> <img border="0" src="../images/cats_icon.gif" /></a> </td> </tr> <tr> <td> <a href="<c:url value="/shop/viewCategory.do?categoryId=REPTILES"/>"> <img border="0" src="../images/reptiles_icon.gif" /></a> </td> </tr> <tr> <td> <a href="<c:url value="/shop/viewCategory.do?categoryId=BIRDS"/>"> <img border="0" src="../images/birds_icon.gif" /></a> </td> </tr> </tbody> </table> </td> <td align="center" bgcolor="white" height="300" width="100%"> <!-- MAIN IMAGE --> <map name="estoremap"><area alt="Birds" coords="72,2,280,250" href="viewCategory.do?categoryId=BIRDS" shape="RECT" /> <area alt="Fish" coords="2,180,72,250" href="viewCategory.do?categoryId=FISH" shape="RECT" /> <area alt="Dogs" coords="60,250,130,320" href="viewCategory.do?categoryId=DOGS" shape="RECT" /> <area alt="Reptiles" coords="140,270,210,340" href="viewCategory.do?categoryId=REPTILES" shape="RECT" /> <area alt="Cats" coords="225,240,295,310" href="viewCategory.do?categoryId=CATS" shape="RECT" /> <area alt="Birds" coords="280,180,350,250" href="viewCategory.do?categoryId=BIRDS" shape="RECT" /></map> <img border="0" height="355" src="../images/splash.gif" align="center" usemap="#estoremap" width="350" /> </td></tr></tbody></table></td></tr> </tbody> </table> <%@ include file="IncludeBanner.jsp" %> <%@ include file="IncludeBottom.jsp" %>
zzh-simple-hr
Zjpetstore/webapp/WEB-INF/jsp/struts/index.jsp
Java Server Pages
art
3,027
<%@ include file="IncludeTop.jsp" %> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr><td valign="top" width="20%" align="left"> <table align="left" bgcolor="#008800" border="0" cellspacing="2" cellpadding="2"> <tr><td bgcolor="#FFFF88"> <a href="<c:url value="/shop/viewCart.do"/>"><b><font color="BLACK" size="2">&lt;&lt; Shopping Cart</font></b></a> </td></tr> </table> </td> <td valign="top" align="center"> <h2 align="center">Checkout Summary</h2> <table align="center" bgcolor="#008800" border="0" cellspacing="2" cellpadding="5"> <tr bgcolor="#cccccc"> <td><b>Item ID</b></td> <td><b>Product ID</b></td> <td><b>Description</b></td> <td><b>In Stock?</b></td> <td><b>Quantity</b></td> <td><b>List Price</b></td> <td><b>Total Cost</b></td> </tr> <c:forEach var="cartItem" items="${cartForm.cart.cartItemList.pageList}"> <tr bgcolor="#FFFF88"> <td><b> <a href="<c:url value="/shop/viewItem.do"><c:param name="itemId" value="${cartItem.item.itemId}"/></c:url>"> <c:out value="${cartItem.item.itemId}"/> </a></b></td> <td><c:out value="${cartItem.item.productId}"/></td> <td> <c:out value="${cartItem.item.attribute1}"/> <c:out value="${cartItem.item.attribute2}"/> <c:out value="${cartItem.item.attribute3}"/> <c:out value="${cartItem.item.attribute4}"/> <c:out value="${cartItem.item.attribute5}"/> <c:out value="${cartItem.item.product.name}"/> </td> <td align="center"><c:out value="${cartItem.inStock}"/></td> <td align="center"> <c:out value="${cartItem.quantity}"/> </td> <td align="right"><fmt:formatNumber value="${cartItem.item.listPrice}" pattern="$#,##0.00" /></td> <td align="right"><fmt:formatNumber value="${cartItem.totalPrice}" pattern="$#,##0.00" /></td> </tr> </c:forEach> <tr bgcolor="#FFFF88"> <td colspan="7" align="right"> <b>Sub Total: <fmt:formatNumber value="${cartForm.cart.subTotal}" pattern="$#,##0.00" /></b><br /> </td> </tr> </table> <center> <c:if test="${!cartForm.cart.cartItemList.firstPage}"> <a href="checkout.do?page=previousCart"><font color="green"><B>&lt;&lt; Prev</B></font></a> </c:if> <c:if test="${!cartForm.cart.cartItemList.lastPage}"> <a href="checkout.do?page=nextCart"><font color="green"><B>Next &gt;&gt;</B></font></a> </c:if> </center> <br> <center><a href="<c:url value="/shop/newOrderForm.do"/>"><img border="0" src="../images/button_continue.gif" /></a></center> </td> <td valign="top" width="20%" align="right">&nbsp;</td> </tr> </table> <%@ include file="IncludeBottom.jsp" %>
zzh-simple-hr
Zjpetstore/webapp/WEB-INF/jsp/struts/Checkout.jsp
Java Server Pages
art
2,614
<p>&nbsp;</p> <table align="center"> <tr> <td> <a href="http://www.springframework.org"> <img border="0" align="center" src="../images/poweredBySpring.gif" alt="Powered by the Spring Framework"/> </a> </td> <td> <a href="http://www.ibatis.com"> <img border="0" align="center" src="../images/poweredby.gif" alt="Powered by iBATIS"/> </a> </td> </tr> </table> <p align="center"> (Currently running on the Struts web tier) </p>
zzh-simple-hr
Zjpetstore/webapp/WEB-INF/jsp/struts/IncludeBottom.jsp
Java Server Pages
art
480
<%@ include file="IncludeTop.jsp" %> <table align="left" bgcolor="#008800" border="0" cellspacing="2" cellpadding="2"> <tr><td bgcolor="#FFFF88"> <a href="<c:url value="/shop/index.do"/>"><b><font color="BLACK" size="2">&lt;&lt; Main Menu</font></b></a> </td></tr> <tr><td bgcolor="#FFFF88"> <%-- <html:link paramId="orderId" paramName="order" paramProperty="orderId" page="/shop/viewOrder.do?webservice=true"><b><font color="BLACK" size="2">Use Web Service</font></b></c:url> --%> </td></tr> </table> <c:if test="${!empty message}"> <center><b><c:out value="${message}"/></b></center> </c:if> <p> <table width="60%" align="center" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFF88"> <tr bgcolor="#FFFF88"><td align="center" colspan="2"> <font size="4"><b>Order #<c:out value="${order.orderId}"/></b></font> <br /><font size="3"><b><fmt:formatDate value="${order.orderDate}" pattern="yyyy/MM/dd hh:mm:ss" /></b></font> </td></tr> <tr bgcolor="#FFFF88"><td colspan="2"> <font color="GREEN" size="4"><b>Payment Details</b></font> </td></tr> <tr bgcolor="#FFFF88"><td> Card Type:</td><td> <c:out value="${order.cardType}"/> </td></tr> <tr bgcolor="#FFFF88"><td> Card Number:</td><td><c:out value="${order.creditCard}"/> <font color="red" size="2">* Fake number!</font> </td></tr> <tr bgcolor="#FFFF88"><td> Expiry Date (MM/YYYY):</td><td><c:out value="${order.expiryDate}"/> </td></tr> <tr bgcolor="#FFFF88"><td colspan="2"> <font color="GREEN" size="4"><b>Billing Address</b></font> </td></tr> <tr bgcolor="#FFFF88"><td> First name:</td><td><c:out value="${order.billToFirstName}"/> </td></tr> <tr bgcolor="#FFFF88"><td> Last name:</td><td><c:out value="${order.billToLastName}"/> </td></tr> <tr bgcolor="#FFFF88"><td> Address 1:</td><td><c:out value="${order.billAddress1}"/> </td></tr> <tr bgcolor="#FFFF88"><td> Address 2:</td><td><c:out value="${order.billAddress2}"/> </td></tr> <tr bgcolor="#FFFF88"><td> City: </td><td><c:out value="${order.billCity}"/> </td></tr> <tr bgcolor="#FFFF88"><td> State:</td><td><c:out value="${order.billState}"/> </td></tr> <tr bgcolor="#FFFF88"><td> Zip:</td><td><c:out value="${order.billZip}"/> </td></tr> <tr bgcolor="#FFFF88"><td> Country: </td><td><c:out value="${order.billCountry}"/> </td></tr> <tr bgcolor="#FFFF88"><td colspan="2"> <font color="GREEN" size="4"><b>Shipping Address</b></font> </td></tr><tr bgcolor="#FFFF88"><td> First name:</td><td><c:out value="${order.shipToFirstName}"/> </td></tr> <tr bgcolor="#FFFF88"><td> Last name:</td><td><c:out value="${order.shipToLastName}"/> </td></tr> <tr bgcolor="#FFFF88"><td> Address 1:</td><td><c:out value="${order.shipAddress1}"/> </td></tr> <tr bgcolor="#FFFF88"><td> Address 2:</td><td><c:out value="${order.shipAddress2}"/> </td></tr> <tr bgcolor="#FFFF88"><td> City: </td><td><c:out value="${order.shipCity}"/> </td></tr> <tr bgcolor="#FFFF88"><td> State:</td><td><c:out value="${order.shipState}"/> </td></tr> <tr bgcolor="#FFFF88"><td> Zip:</td><td><c:out value="${order.shipZip}"/> </td></tr> <tr bgcolor="#FFFF88"><td> Country: </td><td><c:out value="${order.shipCountry}"/> </td></tr> <tr bgcolor="#FFFF88"><td> Courier: </td><td><c:out value="${order.courier}"/> </td></tr> <tr bgcolor="#FFFF88"><td colspan="2"> <b><font color="GREEN" size="4">Status:</font> <c:out value="${order.status}"/></b> </td></tr> <tr bgcolor="#FFFF88"><td colspan="2"> <table width="100%" align="center" bgcolor="#008800" border="0" cellspacing="2" cellpadding="3"> <tr bgcolor="#CCCCCC"> <td><b>Item ID</b></td> <td><b>Description</b></td> <td><b>Quantity</b></td> <td><b>Price</b></td> <td><b>Total Cost</b></td> </tr> <c:forEach var="lineItem" items="${order.lineItems}"> <tr bgcolor="#FFFF88"> <td><b><a href="<c:url value="/shop/viewItem.do"><c:param name="itemId" value="${lineItem.itemId}"/></c:url>"> <font color="BLACK"><c:out value="${lineItem.itemId}"/></font> </a></b></td> <td> <c:out value="${lineItem.item.attribute1}"/> <c:out value="${lineItem.item.attribute2}"/> <c:out value="${lineItem.item.attribute3}"/> <c:out value="${lineItem.item.attribute4}"/> <c:out value="${lineItem.item.attribute5}"/> <c:out value="${lineItem.item.product.name}"/> </td> <td><c:out value="${lineItem.quantity}"/></td> <td align="right"><fmt:formatNumber value="${lineItem.unitPrice}" pattern="$#,##0.00"/></td> <td align="right"><fmt:formatNumber value="${lineItem.totalPrice}" pattern="$#,##0.00"/></td> </tr> </c:forEach> <tr bgcolor="#FFFF88"> <td colspan="5" align="right"><b>Total: <fmt:formatNumber value="${order.totalPrice}" pattern="$#,##0.00"/></b></td> </tr> </table> </td></tr> </table> <%@ include file="IncludeBottom.jsp" %>
zzh-simple-hr
Zjpetstore/webapp/WEB-INF/jsp/struts/ViewOrder.jsp
Java Server Pages
art
4,846
<%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <html><head><title>JPetStore Demo</title> <meta content="text/html; charset=windows-1252" http-equiv="Content-Type" /> <META HTTP-EQUIV="Cache-Control" CONTENT="max-age=0"> <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache"> <meta http-equiv="expires" content="0"> <META HTTP-EQUIV="Expires" CONTENT="Tue, 01 Jan 1980 1:00:00 GMT"> <META HTTP-EQUIV="Pragma" CONTENT="no-cache"> </head> <body bgcolor="white"> <table background="../images/bkg-topbar.gif" border="0" cellspacing="0" cellpadding="5" width="100%"> <tbody> <tr> <td><a href="<c:url value="/shop/index.do"/>"><img border="0" src="../images/logo-topbar.gif" /></a></td> <td align="right"><a href="<c:url value="/shop/viewCart.do"/>"><img border="0" name="img_cart" src="../images/cart.gif" /></a> <img border="0" src="../images/separator.gif" /> <c:if test="${empty accountForm.account}" > <a href="<c:url value="/shop/signonForm.do"/>"><img border="0" name="img_signin" src="../images/sign-in.gif" /></a> </c:if> <c:if test="${!empty accountForm.account}" > <a href="<c:url value="/shop/signon.do?signoff=true"/>"><img border="0" name="img_signout" src="../images/sign-out.gif" /></a> <img border="0" src="../images/separator.gif" /> <a href="<c:url value="/shop/editAccountForm.do"/>"><img border="0" name="img_myaccount" src="../images/my_account.gif" /></a> </c:if> <img border="0" src="../images/separator.gif" /><a href="../help.html"><img border="0" name="img_help" src="../images/help.gif" /></a> </td> <td align="left" valign="bottom"> <form action="<c:url value="/shop/searchProducts.do"/>" method="post"> <input type="hidden" name="search" value="true"/> <input name="keyword" size="14"/>&nbsp;<input border="0" src="../images/search.gif" type="image" name="search"/> </form> </td> </tr> </tbody> </table> <%@ include file="IncludeQuickHeader.jsp" %> <!-- Support for non-traditional but simpler use of errors... --> <c:if test="${!empty errors}"> <c:forEach var="error" items="${errors}"> <B><FONT color=RED> <BR><c:out value="${error}"/> </FONT></B> </c:forEach> </c:if>
zzh-simple-hr
Zjpetstore/webapp/WEB-INF/jsp/struts/IncludeTop.jsp
Java Server Pages
art
2,389
<%@ include file="IncludeTop.jsp" %> <table align="left" bgcolor="#008800" border="0" cellspacing="2" cellpadding="2"> <tr><td bgcolor="#FFFF88"> <a href="<c:url value="/shop/index.do"/>"><b><font color="BLACK" size="2"/>&lt;&lt; Main Menu</font></b></a> </td></tr> </table> <p> <center> <h2><c:out value="${category.name}"/></h2> </center> <table align="center" bgcolor="#008800" border="0" cellspacing="2" cellpadding="3"> <tr bgcolor="#CCCCCC"> <td><b>Product ID</b></td> <td><b>Name</b></td> </tr> <c:forEach var="product" items="${productList.pageList}"> <tr bgcolor="#FFFF88"> <td><b><a href="<c:url value="/shop/viewProduct.do"><c:param name="productId" value="${product.productId}"/></c:url>"> <font color="BLACK"><c:out value="${product.productId}"/></font> </a></b></td> <td><c:out value="${product.name}"/></td> </tr> </c:forEach> <tr><td> <c:if test="${!productList.firstPage}"> <a href="?page=previous"><font color="white"><B>&lt;&lt; Prev</B></font></a> </c:if> <c:if test="${!productList.lastPage}"> <a href="?page=next"><font color="white"><B>Next &gt;&gt;</B></font></a> </c:if> </td></tr> </table> <%@ include file="IncludeBottom.jsp" %></p></p>
zzh-simple-hr
Zjpetstore/webapp/WEB-INF/jsp/struts/Category.jsp
Java Server Pages
art
1,241
<%@ include file="IncludeTop.jsp" %> <%@ taglib prefix="html" uri="http://jakarta.apache.org/struts/tags-html" %> <html:form action="/shop/newOrder.do" styleId="workingOrderForm" method="post" > <TABLE bgcolor="#008800" border=0 cellpadding=3 cellspacing=1 bgcolor="#FFFF88"> <TR bgcolor="#FFFF88"><TD colspan=2> <FONT color=GREEN size=4><B>Payment Details</B></FONT> </TD></TR><TR bgcolor="#FFFF88"><TD> Card Type:</TD><TD> <html:select name="workingOrderForm" property="order.cardType"> <html:options name="workingOrderForm" property="creditCardTypes" /> </html:select> </TD></TR> <TR bgcolor="#FFFF88"><TD> Card Number:</TD><TD><html:text name="workingOrderForm" property="order.creditCard" /> <font color=red size=2>* Use a fake number!</font> </TD></TR> <TR bgcolor="#FFFF88"><TD> Expiry Date (MM/YYYY):</TD><TD><html:text name="workingOrderForm" property="order.expiryDate" /> </TD></TR> <TR bgcolor="#FFFF88"><TD colspan=2> <FONT color=GREEN size=4><B>Billing Address</B></FONT> </TD></TR> <TR bgcolor="#FFFF88"><TD> First name:</TD><TD><html:text name="workingOrderForm" property="order.billToFirstName" /> </TD></TR> <TR bgcolor="#FFFF88"><TD> Last name:</TD><TD><html:text name="workingOrderForm" property="order.billToLastName" /> </TD></TR> <TR bgcolor="#FFFF88"><TD> Address 1:</TD><TD><html:text size="40" name="workingOrderForm" property="order.billAddress1" /> </TD></TR> <TR bgcolor="#FFFF88"><TD> Address 2:</TD><TD><html:text size="40" name="workingOrderForm" property="order.billAddress2" /> </TD></TR> <TR bgcolor="#FFFF88"><TD> City: </TD><TD><html:text name="workingOrderForm" property="order.billCity" /> </TD></TR> <TR bgcolor="#FFFF88"><TD> State:</TD><TD><html:text size="4" name="workingOrderForm" property="order.billState" /> </TD></TR> <TR bgcolor="#FFFF88"><TD> Zip:</TD><TD><html:text size="10" name="workingOrderForm" property="order.billZip" /> </TD></TR> <TR bgcolor="#FFFF88"><TD> Country: </TD><TD><html:text size="15" name="workingOrderForm" property="order.billCountry" /> </TD></TR> <TR bgcolor="#FFFF88"><TD colspan=2> <html:checkbox name="workingOrderForm" property="shippingAddressRequired" /> Ship to different address... </TD></TR> </TABLE> <P> <input type="image" src="../images/button_submit.gif"> </html:form> <%@ include file="IncludeBottom.jsp" %>
zzh-simple-hr
Zjpetstore/webapp/WEB-INF/jsp/struts/NewOrderForm.jsp
Java Server Pages
art
2,368