当前位置: 首页>>代码示例>>Java>>正文


Java KeyFactory.stringToKey方法代码示例

本文整理汇总了Java中com.google.appengine.api.datastore.KeyFactory.stringToKey方法的典型用法代码示例。如果您正苦于以下问题:Java KeyFactory.stringToKey方法的具体用法?Java KeyFactory.stringToKey怎么用?Java KeyFactory.stringToKey使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.google.appengine.api.datastore.KeyFactory的用法示例。


在下文中一共展示了KeyFactory.stringToKey方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: deleteUserGroup

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
/**
 * Delete a User Group from a mobile device
 * @param req:
 * 			the HTTP request
 * @param customer:
 * 			the customer who is executing the action
 * @throws Exception
 * @throws IOException 
 * @throws UnauthorizedUserOperationException
 */
public void deleteUserGroup(HttpServletRequest req, 
		Customer customer) 
				throws Exception, IOException,
				UnauthorizedUserOperationException {
	
	String userGroupKeyString = req.getParameter("g_key");
	Key userGroupKey = KeyFactory.stringToKey(userGroupKeyString);
    
	// Check that the group belongs to the user
    if (!userGroupKey.getParent().equals(customer.getKey())) {
        throw new UnauthorizedUserOperationException(customer.getUser(), 
        		"This group does not belong to the given user.");
    }
	
	UserGroupManager.deleteUserGroup(userGroupKey);
}
 
开发者ID:gfigueroa,项目名称:internet-radio-gae,代码行数:27,代码来源:CloudSyncServlet.java

示例2: getAccountKeyByUser

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
/**
 * Returns the Account key associated with the specified user.
 * @param pm   reference to the persistence manager
 * @param user user to return the account key for
 * @return the Account key associated with the specified user; or <code>null</code> if no account is associated with the specified user
 */
public static Key getAccountKeyByUser( final PersistenceManager pm, final User user ) {
	final String memcacheKey = CACHE_KEY_USER_ACCOUNT_KEY_PREFIX + user.getEmail();
	final String accountKeyString = (String) memcacheService.get( memcacheKey );
	if ( accountKeyString != null )
		return KeyFactory.stringToKey( accountKeyString );
	
	final Query q = new Query( Account.class.getSimpleName() );
	q.setFilter( new FilterPredicate( "user", FilterOperator.EQUAL, user ) );
	q.setKeysOnly();
	final List< Entity > entityList = DatastoreServiceFactory.getDatastoreService().prepare( q ).asList( FetchOptions.Builder.withDefaults() );
	if ( entityList.isEmpty() )
		return null;
	
	final Key accountKey = entityList.get( 0 ).getKey();
	try {
		memcacheService.put( memcacheKey, KeyFactory.keyToString( accountKey ) );
	}
	catch ( final MemcacheServiceException mse ) {
		LOGGER.log( Level.WARNING, "Failed to put key to memcache: " + memcacheKey, mse );
		// Ignore memcache errors, do not prevent serving user request
	}
	
	return accountKey;
}
 
开发者ID:icza,项目名称:sc2gears,代码行数:31,代码来源:CachingService.java

示例3: getAccountKeyByAuthKey

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
/**
 * Returns the Account key associated with the specified authorization key.
 * @param pm               reference to the persistence manager
 * @param authorizationKey authorization key to return the account key for
 * @return the Account key associated with the specified authorization key; or <code>null</code> if the authorization key is invalid
 */
public static Key getAccountKeyByAuthKey( final PersistenceManager pm, final String authorizationKey ) {
	final String memcacheKey = CACHE_KEY_AUTH_KEY_ACCOUNT_KEY_PREFIX + authorizationKey;
	final String accountKeyString = (String) memcacheService.get( memcacheKey );
	if ( accountKeyString != null )
		return KeyFactory.stringToKey( accountKeyString );
	
	final Query q = new Query( Account.class.getSimpleName() );
	q.setFilter( new FilterPredicate( "authorizationKey", FilterOperator.EQUAL, authorizationKey ) );
	q.setKeysOnly();
	final List< Entity > entityList = DatastoreServiceFactory.getDatastoreService().prepare( q ).asList( FetchOptions.Builder.withDefaults() );
	if ( entityList.isEmpty() )
		return null;
	
	final Key accountKey = entityList.get( 0 ).getKey();
	try {
		memcacheService.put( memcacheKey, KeyFactory.keyToString( accountKey ) );
	}
	catch ( final MemcacheServiceException mse ) {
		LOGGER.log( Level.WARNING, "Failed to put key to memcache: " + memcacheKey, mse );
		// Ignore memcache errors, do not prevent serving user request
	}
	
	return accountKey;
}
 
开发者ID:icza,项目名称:sc2gears,代码行数:31,代码来源:CachingService.java

示例4: keyToString_getsPerson

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
@Test
public void keyToString_getsPerson() throws Exception {
  Entity p = new Entity("Person");
  p.setProperty("relationship", "Me");
  datastore.put(p);
  Key k = p.getKey();

  // [START generating_keys_3]
  String personKeyStr = KeyFactory.keyToString(k);

  // Some time later (for example, after using personKeyStr in a link).
  Key personKey = KeyFactory.stringToKey(personKeyStr);
  Entity person = datastore.get(personKey);
  // [END generating_keys_3]

  assertThat(personKey).isEqualTo(k);
  assertThat((String) person.getProperty("relationship"))
      .named("person.relationship")
      .isEqualTo("Me");
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:21,代码来源:EntitiesTest.java

示例5: run

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
@Override
public void run() {
  // Get raw key strings from request
  ImmutableList.Builder<Object> ofyDeletionsBuilder = new ImmutableList.Builder<>();
  ImmutableList.Builder<Key> rawDeletionsBuilder = new ImmutableList.Builder<>();
  for (String rawKeyString : Splitter.on(',').split(rawKeys)) {
    // Convert raw keys string to real keys. Try to load it from Objectify if it's a registered
    // type, and fall back to DatastoreService if its not registered.
    Key rawKey = KeyFactory.stringToKey(rawKeyString);
    Optional<Object> ofyEntity = loadOfyEntity(rawKey);
    if (ofyEntity.isPresent()) {
      ofyDeletionsBuilder.add(ofyEntity.get());
      continue;
    }
    Optional<Entity> rawEntity = loadRawEntity(rawKey);
    if (rawEntity.isPresent()) {
      rawDeletionsBuilder.add(rawEntity.get().getKey());
      continue;
    }
    // The entity could not be found by either Objectify or the Datastore service
    throw new BadRequestException("Could not find entity with key " + rawKeyString);
  }
  // Delete raw entities.
  ImmutableList<Key> rawDeletions = rawDeletionsBuilder.build();
  getDatastoreService().delete(rawDeletions);
  // Delete ofy entities.
  final ImmutableList<Object> ofyDeletions = ofyDeletionsBuilder.build();
  ofy().transactNew(new VoidWork() {
      @Override
      public void vrun() {
        ofy().delete().entities(ofyDeletions).now();
      }});
  String message = String.format(
      "Deleted %d raw entities and %d registered entities",
      rawDeletions.size(),
      ofyDeletions.size());
  logger.info(message);
  response.setPayload(message);
}
 
开发者ID:google,项目名称:nomulus,代码行数:40,代码来源:DeleteEntityAction.java

示例6: carryOutDelete

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
/**
 * Carry out a delete.
 */
private void carryOutDelete(HttpServletRequest req, HttpServletResponse resp,
		String type)
		throws ServletException, IOException {
	
	// Check user email and password
	String userEmailString = req.getParameter("userEmail");
	Email userEmail = new Email(userEmailString);
	String userPassword = req.getParameter("userPassword");
       Station station = StationManager.getStation(userEmail);
       if (!station.getUser().validateUser(userEmail, userPassword)) {
           resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
               	"User e-mail and password don't match.");
           return;
       }
       
       // Check type
       String keyString = req.getParameter("key");
       Key key = KeyFactory.stringToKey(keyString);
       if (type.equalsIgnoreCase("program")) {
       	ProgramManager.deleteProgram(key);
       }
       else if (type.equalsIgnoreCase("playlist")) {
       	PlaylistManager.deletePlaylist(key);
       }
       else if (type.equalsIgnoreCase("channel")) {
       	ChannelManager.deleteChannel(key);
       }
	else {
    	resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
           		"Invalid type.");
    	return;
	}
       
       resp.sendRedirect(thisServlet + "?msg=success&action=delete");
}
 
开发者ID:gfigueroa,项目名称:internet-radio-gae,代码行数:39,代码来源:StationUploadServlet.java

示例7: syncMasterPost

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
/**
 * Executes the sync master post upload function by
 * a mobile device
 * @param req:
 * 			the HTTP request
 * @param customer:
 * 			the customer who is executing the action
 * @throws Exception
 * @throws IOException 
 * @throws MissingRequiredFieldsException 
 */
public void syncMasterPost(HttpServletRequest req,
		Customer customer) 
				throws Exception, IOException, 
				MissingRequiredFieldsException {
	
	String groupKeysString = req.getParameter("g_keys");
    String[] groupKeyTokens = groupKeysString.split(",");
    ArrayList<Key> groupKeys = new ArrayList<Key>();
    if (!groupKeysString.isEmpty()) {
        for (String keyToken : groupKeyTokens) {
        	Key groupKey = KeyFactory.stringToKey(keyToken);
        	groupKeys.add(groupKey);
        }
    }
    
    String messageText = req.getParameter("m_text");

    CloudSyncCommand cloudSyncCommand = new CloudSyncCommand(
    		customer.getKey(), // TODO: Master is owner by default
    		groupKeys,
    		messageText
    		);
    
    CustomerManager.updateCustomerCloudSyncCommand(
    		customer.getUser().getUserEmail(), 
    		cloudSyncCommand);
}
 
开发者ID:gfigueroa,项目名称:internet-radio-gae,代码行数:39,代码来源:CloudSyncServlet.java

示例8: manageGroupMember

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
/**
   * Manage a User in a User Group from a mobile device.
   * Users can be either added or deleted with this function
   * depending on the "add" parameter.
   * @param req:
   * 			the HTTP request
   * @param customer:
   * 			the customer who is executing the action
   * @param add:
   * 			whether the action to perform is add or not
   * @throws Exception
   * @throws IOException 
   * @throws UnauthorizedUserOperationException
   * @throws InexistentObjectException
   */
  public void manageGroupMember(HttpServletRequest req,
  		Customer customer, boolean add) 
  				throws Exception, IOException, 
  				UnauthorizedUserOperationException,
  				InexistentObjectException {
  	
  	String userGroupKeyString = req.getParameter("g_key");
  	Key userGroupKey = KeyFactory.stringToKey(userGroupKeyString);
      
  	// Check that the group belongs to the user
      if (!userGroupKey.getParent().equals(customer.getKey())) {
          throw new UnauthorizedUserOperationException(customer.getUser(), 
          		"This group does not belong to the given user.");
      }
      
  	String memberEmail = req.getParameter("m_email");
  	
  	// Check if the user to add/delete exists in the datastore
  	Key memberKey = KeyFactory.createKey(
  			Customer.class.getSimpleName(), memberEmail);
if (!DatastoreManager.entityExists(Customer.class, memberKey)) {
	throw new InexistentObjectException(customer, "User \"" + 
			customer.getUser().getUserEmail().getEmail() + 
			"\" doesn't exist in the datastore.");
}

if (add) {
	UserGroupManager.addMemeberToUserGroup(userGroupKey, memberEmail);
}
else {
	UserGroupManager.removeMemberFromUserGroup(userGroupKey, memberEmail);
}
  }
 
开发者ID:gfigueroa,项目名称:internet-radio-gae,代码行数:49,代码来源:CloudSyncServlet.java

示例9: addToFavorites

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
/**
   * Add to Favorites from a mobile device
   * @param req:
   * 			the HTTP request
   * @param customer:
   * 			the customer who is executing the action
   * @throws Exception
   * @throws IOException 
   * @throws MissingRequiredFieldsException 
   */
  public void addToFavorites(HttpServletRequest req,
  		Customer customer) 
  				throws Exception, IOException, 
  				MissingRequiredFieldsException {
  	
  	UserRecommendation.UserRecommendationSuperType 
  			userRecommendationSuperType = 
  			UserRecommendation.UserRecommendationSuperType.FAVORITE;
  	
  	String userRecommendationTypeString = req.getParameter("r_type");
  	UserRecommendation.UserRecommendationType userRecommendationType =
  			UserRecommendation.getUserRecommendationTypeFromString(
  					userRecommendationTypeString);
  	
  	String userRecommendationComment = req.getParameter("r_comment");
  	
  	String itemKeyString = req.getParameter("i_key");
  	Key itemKey = KeyFactory.stringToKey(itemKeyString);
  	
ArrayList<UserRecommendationRecipient> userRecommendationRecipients =
		new ArrayList<UserRecommendationRecipient>();
  	
  	userRecommendationRecipients.add(new UserRecommendationRecipient(
  			customer.getKey(),
  			null
  			));
  	
UserRecommendation userRecommendation = 
  			new UserRecommendation(
  					userRecommendationSuperType,
  					userRecommendationType,
  					userRecommendationComment,
  					itemKey,
  					userRecommendationRecipients
  					);

UserRecommendationManager.putUserRecommendation(
		customer.getKey(), userRecommendation);
  }
 
开发者ID:gfigueroa,项目名称:internet-radio-gae,代码行数:50,代码来源:CloudSyncServlet.java

示例10: doGet

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
	
	HttpSession session = req.getSession(true);
    User user = (User) session.getAttribute("user");
    
    // Check that an administrator is carrying out the action
 if (user == null || user.getUserType() != User.Type.ADMINISTRATOR) {
 	resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
     return;
 }
	
    // Lets check the action required by the jsp
    String action = req.getParameter("action");

    if (action.equals("delete")) {
    	
        // retrieve the key     
    	String keyString = req.getParameter("k");
  		Key key = KeyFactory.stringToKey(keyString);

        // deleting a user
        switch(req.getParameter("u_type").charAt(0)){
            case 'A':
                Administrator admin = 
                    AdministratorManager.getAdministrator(key);
                AdministratorManager.deleteAdministrator(admin);
                resp.sendRedirect(listAdminJSP + "?msg=success&action=" + action);
                return;
            case 'S':
                Station station = StationManager.getStation(key);
                SystemManager.updateStationListVersion();
                SystemManager.updateStationListVersion();
                StationTypeManager.updateStationTypeVersion(station.getStationType());
                StationManager.deleteStation(station);
                resp.sendRedirect(listStationJSP + "?msg=success&action=" + action);
                break;
            case 'C':
                Customer customer = CustomerManager.getCustomer(key);
                CustomerManager.deleteCustomer(customer);
                resp.sendRedirect(listCustomerJSP + "?msg=success&action=" + action);
                break;
            default:
                assert(false); // there is no other type
        }
    }
}
 
开发者ID:gfigueroa,项目名称:internet-radio-gae,代码行数:48,代码来源:ManageUserServlet.java

示例11: editStationAudio_File

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
/**
 * Edit a station audio.
 * @param reader
 * 			: the JsonReader instance
 * @throws IOException 
 * @throws MissingRequiredFieldsException 
 * @throws ObjectExistsInDatastoreException 
 */
private void editStationAudio_File(JsonReader reader)
		throws IOException, MissingRequiredFieldsException, 
		ObjectExistsInDatastoreException {

	// Station audio attributes
	StationAudio stationAudio = null;
	Key stationAudioKey = null;
	StationAudio.StationAudioType stationAudioType = null;
	String stationAudioName = null;
	Double stationAudioDuration = null;
	
	while (reader.hasNext()) {
	
		String fieldName = reader.nextName();
		if (fieldName.equals("stationAudioKey")) {
			String stationAudioKeyString = reader.nextString();
			stationAudioKey = KeyFactory.stringToKey(stationAudioKeyString);
			stationAudio = StationAudioManager.getStationAudio(stationAudioKey);
		}
		else if (fieldName.equals("stationAudioType")) {
			String stationAudioTypeString = reader.nextString();
			stationAudioType = 
					StationAudio.getStationAudioTypeFromString(stationAudioTypeString);
		}
		else if (fieldName.equals("stationAudioName")) {
			stationAudioName = reader.nextString();
		}
		else if (fieldName.equals("stationAudioDuration")) {
			stationAudioDuration = reader.nextDouble();
		}
		else {
			reader.skipValue(); //avoid some unhandled events
		}
    }
	
	StationAudioManager.updateStationAudioAttributes(
			stationAudioKey, 
			stationAudioType, 
			stationAudioName, 
			stationAudio.getStationAudioMultimediaContent(), 
			stationAudioDuration,
			stationAudio.getStationAudioFormat());
}
 
开发者ID:gfigueroa,项目名称:internet-radio-gae,代码行数:52,代码来源:StationUploadServlet.java

示例12: doGet

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
	
	// Check that an actual user is carrying out the action
	HttpSession session = req.getSession(true);
    User user = (User) session.getAttribute("user");
    if (user == null || user.getUserType() != User.Type.STATION) {
    	resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }
	
    // Lets check the action required by the jsp
    String action = req.getParameter("action");

    if (action.equals("delete")) {
    	
    	String type = req.getParameter("type");
    	
    	// Key of object to delete
    	Key key = KeyFactory.stringToKey(req.getParameter("k"));

    	String redirectURL = "?msg=success&action=" + action;
    	
        // Secondary Tracks
        if (type.equalsIgnoreCase("st")) {
        	SecondaryTrackManager.deleteSecondaryTrack(key);
        	
        	redirectURL = editProgramJSP + redirectURL + "&k=" + 
        			KeyFactory.keyToString(key.getParent());
        }
        // Slides
        else if (type.equalsIgnoreCase("slide")) {
        	SlideManager.deleteSlide(key);
        	
        	redirectURL = editProgramJSP + redirectURL + "&k=" + 
        			KeyFactory.keyToString(key.getParent());
        }
        else {
	    	resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
         		"Invalid type.");
	    	return;
        }
        
        // If success
        resp.sendRedirect(redirectURL);
    }
}
 
开发者ID:gfigueroa,项目名称:internet-radio-gae,代码行数:48,代码来源:ManageProgramServlet.java

示例13: doGet

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
/**
    * Respond to servlet GET requests
    */
   public void doGet(HttpServletRequest req, HttpServletResponse resp)
           throws IOException {
   	
    // Lets check the action required by the jsp
    String message = req.getParameter("msg");
    String action = req.getParameter("action");

    if (message.equals("success")) {
    	
    	// We return information about the file in JSON format
    	if (action.equalsIgnoreCase("upload")) {
    		
    		String type = req.getParameter("type");
    		String datastoreObjectKeyString = 
    				req.getParameter("datastoreObjectKey");
    		Key datastoreObjectKey = KeyFactory.stringToKey(datastoreObjectKeyString);
    		BlobKey fileKey = null;
    		String fileKeyString = null;
    		String jsonString = null;
    		
    		// Check type
    		if (type.equalsIgnoreCase("audio_music") || 
    				type.equalsIgnoreCase("audio_voice")) {
    			
    			StationAudio stationAudio = 
    					StationAudioManager.getStationAudio(datastoreObjectKey);
    			
    			fileKey = stationAudio.getStationAudioMultimediaContent();
    		}
    		else if (type.equalsIgnoreCase("image")) {
    			StationImage stationImage = 
    					StationImageManager.getStationImage(datastoreObjectKey);
    			
    			fileKey = stationImage.getStationImageMultimediaContent();
    		}
    		
    		fileKeyString = fileKey.getKeyString();
	    	BlobInfoFactory bif = new BlobInfoFactory();
	    	BlobInfo blobInfo = bif.loadBlobInfo(fileKey);
	    	String fileName = blobInfo.getFilename();
	    	
	    	jsonString = "{" + "\n" +
	    			"\"datastoreObjectKey\":" + "\"" + datastoreObjectKeyString + "\"," + "\n" +
	    			"\"fileKey\":" + "\"" + fileKeyString + "\"," + "\n" +
	    			"\"fileName\":" + "\"" + fileName + "\"\n" +
	    			"}";
	    	
	    	log.info("jsonString: " + jsonString);
	    	
	    	resp.setContentType("application/json;charset=UTF-8");
	    	resp.setCharacterEncoding("UTF-8");
	    	resp.getWriter().println(jsonString);
    	}
    	else if (action.equals("delete")){
    		resp.getWriter().println("File deleted successfully.");
    	}
    }
}
 
开发者ID:gfigueroa,项目名称:internet-radio-gae,代码行数:62,代码来源:BinaryFileUploadServlet.java

示例14: toJson

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
/**
* Returns station as a JSON object.
* @return A station in JSON format
*/
  @Get("json")
  public StationSimple toJson() {
  	
  	String queryInfo = (String) getRequest().getAttributes()
              .get("queryinfo");

   char searchBy = queryInfo.charAt(0);
   String searchString = queryInfo.substring(2);
       
   Key stationKey = KeyFactory.stringToKey(searchString);
   log.info("Query: " + searchBy + "=" + searchString);

   // Get station
   Station station = StationManager.getStation(stationKey);
   
  	// First, get and create the channels
  	ArrayList<ChannelSimple> simpleChannels = new ArrayList<ChannelSimple>();
  	List<Channel> channels = ChannelManager.getStationChannels(station.getKey());
  	for (Channel channel : channels) {
  		Key channelKey = channel.getKey();	// TODO: Remove?
  		BlobKey firstSlideBlobKey =// new BlobKey("");
  				ChannelManager.getFirstSlideBlobKey(channel);
  		ChannelSimple channelSimple = new ChannelSimple(
  				KeyFactory.keyToString(channel.getKey()),
  				channel.getChannelName(),
  				channel.getChannelNumber(),
  				firstSlideBlobKey
  				);
  		simpleChannels.add(channelSimple);
  	}
   
  	// Then create the station simple
  	StationSimple stationSimple = new StationSimple(
  			KeyFactory.keyToString(station.getKey()),
  			station.getStationType(),
  			station.getStationPrivilegeLevel(),
  			station.getStationName(),
  			station.getStationNumber(),
  			station.getStationDescription(),
  			RegionManager.getRegion(station.getRegion()).getRegionName(),
  			station.getStationAddress() != null ? 
  					station.getStationAddress().getAddress() : "",
  			station.getStationWebsite() != null ? 
  					station.getStationWebsite().getValue() : "",
  			station.getUser().getUserEmail().getEmail(),
  			station.getStationLogo() != null ? 
  					station.getStationLogo() : new BlobKey(""),
  			station.getStationComments() != null ?
  					station.getStationComments() : "",
  			simpleChannels);

  	return stationSimple;
  }
 
开发者ID:gfigueroa,项目名称:internet-radio-gae,代码行数:58,代码来源:StationProfileResource.java

示例15: toJson

import com.google.appengine.api.datastore.KeyFactory; //导入方法依赖的package包/类
/**
* Returns the playlist list as a JSON object.
* @return An ArrayList of playlist in JSON format
*/
  @Get("json")
  public ArrayList<PlaylistSimple> toJson() {
  	
  	String queryInfo = (String) getRequest().getAttributes()
              .get("queryinfo");

   char searchBy = queryInfo.charAt(0);
   String searchString = queryInfo.substring(2);
       
   Key stationKey = KeyFactory.stringToKey(searchString);
   log.info("Query: " + searchBy + "=" + searchString);

   // Get all the playlists from every station
   List<Playlist> playlistList = PlaylistManager.getStationPlaylists(stationKey);

      ArrayList<PlaylistSimple> playlistListSimple = new ArrayList<PlaylistSimple>();
      for (Playlist playlist : playlistList) {

      	// Create PlaylistMusicFiles
      	List<PlaylistMusicFile> playlistMusicFiles = 
      			PlaylistMusicFileManager.getAllPlaylistMusicFilesFromPlaylist(
      					playlist.getKey(), true);
      	ArrayList<PlaylistMusicFileSimple> playlistMusicFilesSimple = 
      			new ArrayList<PlaylistMusicFileSimple>();
      	for (PlaylistMusicFile playlistMusicFile : playlistMusicFiles) {
      		PlaylistMusicFileSimple playlistMusicFileSimple = 
      				new PlaylistMusicFileSimple(
      						playlistMusicFile.getMusicFileKey(),
      						playlistMusicFile.getPlaylistMusicFileSequenceNumber()
      						);
      		playlistMusicFilesSimple.add(playlistMusicFileSimple);
      	}
      	
      	PlaylistSimple playlistSimple = new PlaylistSimple(
      			KeyFactory.keyToString(playlist.getKey()),
      			playlist.getPlaylistName(),
      			playlistMusicFilesSimple,
      			DateManager.printDateAsString(
      					playlist.getPlaylistCreationDate()),
      			DateManager.printDateAsString(
      					playlist.getPlaylistModificationDate())
      			);
      	
      	playlistListSimple.add(playlistSimple);
      }
      
      return playlistListSimple;
  }
 
开发者ID:gfigueroa,项目名称:internet-radio-gae,代码行数:53,代码来源:PlaylistsResource.java


注:本文中的com.google.appengine.api.datastore.KeyFactory.stringToKey方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。