⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 googlebaseattributesextension.java

📁 google的gdata api包
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
  /**   * Gets all the values of a specific attribute, as a list of   * {@link Location} objects.   *   * @param name attribute name   * @return a list of locations, which might be empty but not null   * @exception NumberFormatException if some value was   *   found that could not be converted   */  public List<Location> getLocationAttributesAsObjects(String name) {    List<? extends GoogleBaseAttribute> attributes =        getAttributes(name, GoogleBaseAttributeType.LOCATION);    List<Location> retval = new ArrayList<Location>(attributes.size());    for (GoogleBaseAttribute attribute : attributes) {      retval.add(ConversionUtil.extractLocation(attribute));    }    return retval;  }  /**   * Adds an attribute of type   * {@link com.google.api.gbase.client.GoogleBaseAttributeType#LOCATION}.   *   * This method will never remove an attribute, even if it has   * the same name as the new attribute. If you would like to set   * an attribute that can only appear once, call   * {@link #removeAttributes(String, GoogleBaseAttributeType)} first.   *   * @param name attribute name   * @param location attribute value   * @return the attribute object that has been created and added to the item   */  public GoogleBaseAttribute addLocationAttribute(String name, String location) {    return addAttribute(new GoogleBaseAttribute(name,        GoogleBaseAttributeType.LOCATION, location));  }  /**   * Adds an attribute of type   * {@link com.google.api.gbase.client.GoogleBaseAttributeType#LOCATION}.   *   * This method will never remove an attribute, even if it has   * the same name as the new attribute. If you would like to set   * an attribute that can only appear once, call   * {@link #removeAttributes(String, GoogleBaseAttributeType)} first.   *   * @param name attribute name   * @param location attribute value   * @return the attribute object that has been created and added to the item   */  public GoogleBaseAttribute addLocationAttribute(String name,      Location location) {    return addAttribute(ConversionUtil.createAttribute(name, location));  }  /**   * Gets the first value of a specific attribute, as a   * {@link com.google.api.gbase.client.DateTimeRange}.   *   * This method does not check the type of the attribute   * that's being queried, it just gets the value and try   * and convert it.   *   * @param name attribute name   * @return value of the attribute or null if no attribute   *   with this name was found on the list   * @exception NumberFormatException if some value was   *   found that could not be converted   */  public DateTimeRange getDateTimeRangeAttribute(String name) {    GoogleBaseAttribute value = getAttribute(name);    if (value == null) {      return null;    }    return ConversionUtil.extractDateTimeRange(value);  }  /**   * Gets all the values of a specific attribute, as a list of   * {@link com.google.api.gbase.client.DateTimeRange}.   *   * This method does not check the type of the attribute   * that's being queried, it just gets the values and try   * and convert them.   *   * @param name attribute name   * @return a list of DateTimeRange, which might be empty but not null   * @exception NumberFormatException if some value was   *   found that could not be converted   */  public List<? extends DateTimeRange> getDateTimeRangeAttributes(String name) {    List<DateTimeRange> retval = new ArrayList<DateTimeRange>();    for (GoogleBaseAttribute attr: attributes) {      if (hasNameAndType(attr, name,                         GoogleBaseAttributeType.DATE_TIME_RANGE)) {        retval.add(ConversionUtil.extractDateTimeRange(attr));      }    }    return retval;  }  /**   * Adds an attribute of type   * {@link GoogleBaseAttributeType#DATE_TIME_RANGE}.   *   * This method will never remove an attribute, even if it has   * the same name as the new attribute. If you would like to set   * an attribute that can only appear once, call   * {@link #removeAttributes(String, GoogleBaseAttributeType)} first.   *   * @param name attribute name   * @param dateTimeRange attribute value   * @return the attribute object that has been created and added to the item   * @exception IllegalArgumentException if the DateTimeRange is an empty   *   range, in which case {@link #addDateTimeAttribute(String,   *   com.google.gdata.data.DateTime)} should be used instead.   */  public GoogleBaseAttribute addDateTimeRangeAttribute(String name,      DateTimeRange dateTimeRange) {    if (dateTimeRange.isDateTimeOnly()) {      // The server would reject such a range      throw new IllegalArgumentException("Empty DateTimeRange. Add " +          "it as a single DateTime using addDateTimeAttribute() instead.");    }    return addAttribute(ConversionUtil.createAttribute(name, dateTimeRange));  }  /**   * Implements   * {@link Extension#generate(XmlWriter, ExtensionProfile)}.   *   * This method generates XML code for the attribute in this extension.   * It is meant to be called by the Google data library.   *   * @param xmlWriter   * @param extensionProfile   */  public void generate(XmlWriter xmlWriter, ExtensionProfile extensionProfile)      throws IOException {    for (GoogleBaseAttribute attribute : attributes) {      String elementName =          convertToElementName(attribute.getAttributeId().getName());      xmlWriter.startElement(GoogleBaseNamespaces.G,                             elementName,                             getXmlAttributes(attribute),                             null);            generateValue(attribute, xmlWriter);      generateSubElements(attribute, xmlWriter);      generateAdjustments(attribute, xmlWriter);            xmlWriter.endElement();    }  }  /**   * Generates XML code for the value of the {@code attribute}.   *   * @param attribute   * @param xmlWriter   * @throws java.io.IOException   */  private void generateValue(GoogleBaseAttribute attribute, XmlWriter xmlWriter)      throws IOException {    if (attribute.hasValue()) {      xmlWriter.characters(attribute.getValueAsString());    }  }    /**   * Generates XML code for all sub-elements of the {@code attribute}.   *    * @param attribute   * @param xmlWriter   * @throws IOException   */  private void generateSubElements(GoogleBaseAttribute attribute,       XmlWriter xmlWriter) throws IOException {    if (attribute.hasSubElements()) {      for (String name : attribute.getSubElementNames()) {        writeXmlNameValue(xmlWriter, GoogleBaseNamespaces.G, name,             attribute.getSubElementValue(name));      }    }  }  /**   * Generates XML code for the adjustments of the {@code attribute}    * ({@code adjusted_value}, {@code adjusted_name}).    *     * @param attribute   * @param xmlWriter   * @throws IOException   */  private void generateAdjustments(GoogleBaseAttribute attribute,       XmlWriter xmlWriter) throws IOException {    if (attribute.hasAdjustments()) {      Adjustments adjustments = attribute.getAdjustments();      if (adjustments.getName() != null) {        writeXmlNameValue(xmlWriter, GoogleBaseNamespaces.GM,             GM_ADJUSTED_NAME_ATTRIBUTE, adjustments.getName());      }      if (adjustments.getValue() != null) {        writeXmlNameValue(xmlWriter, GoogleBaseNamespaces.GM,             GM_ADJUSTED_VALUE_ATTRIBUTE, adjustments.getValue());      }    }  }  /**   * Writes a attribute to the {@code xmlWriter} with the specified    * {@code namespace} and {@code name} and with the text content defined by   * the {@code value}.   *      * @param xmlWriter   * @param namespace   * @param name   * @param value   * @throws IOException   */  private void writeXmlNameValue(XmlWriter xmlWriter, Namespace namespace,       String name, String value) throws IOException {    xmlWriter.startElement(namespace,            convertToElementName(name),            null,            null);    xmlWriter.characters(value);    xmlWriter.endElement();  }  /**   * Converts an attribute name (with space) to an XML   * element name (with underscores).   *   * @param attributeName   * @return corresponding element name   */  private String convertToElementName(String attributeName) {    return attributeName.replace(' ', '_');  }  /**   * Converts an XML element local name (with underscores) to   * an attribute name (with spaces).   *   * @param localName element name without namespace prefix   * @return corresponding attribute name   */  private String convertToAttributeName(String localName) {    return localName.replace('_', ' ');  }  /**   * Returns the XML attributes that should be set to the   * element corresponding to the given   * {@link com.google.api.gbase.client.GoogleBaseAttribute}.   *   * This method is meant to be implemented in subclasses that need   * so set attributes. By default, it defines no attributes and   * simply returns null.   *   * @param attribute   * @return a collection of XML attributes or null   */  private Collection<XmlWriter.Attribute> getXmlAttributes(      GoogleBaseAttribute attribute) {    GoogleBaseAttributeType type = attribute.getAttributeId().getType();    if (type == null) {      return null;    }    List<XmlWriter.Attribute> attributes = new ArrayList<XmlWriter.Attribute>();    attributes.add(new XmlWriter.Attribute("type", type.toString()));    if (attribute.isPrivate()) {      attributes.add(new XmlWriter.Attribute("access", "private"));    }    return attributes;  }  /**   * Given an XML element local name and its attributes, creates   * an {@link com.google.api.gbase.client.GoogleBaseAttribute}.   *   * This method reads the 'type' attribute and set it in the   * {@link GoogleBaseAttribute}.   *   * @param attributeName attribute name, with spaces   * @param xmlAttributes XML attributes for the current element   * @return the GoogleBaseAttribute for the XML tag   */  private GoogleBaseAttribute createExtensionAttribute(      String attributeName, Attributes xmlAttributes) {    String type = xmlAttributes.getValue("type");    String access = xmlAttributes.getValue("access");    boolean privateAccess = "private".equals(access);    return new GoogleBaseAttribute(attributeName,                                   GoogleBaseAttributeType.getInstance(type),                                   privateAccess);  }  /**   * Implements   * {@link Extension#getHandler(ExtensionProfile, String, String, Attributes)}.   *   * This method returns a handler object that can parse an attribute in   * the current namespace and add the corresponding {@link GoogleBaseAttribute}   * into the list.   *   * It is meant to be called by the Google data library.   */  public XmlParser.ElementHandler getHandler(ExtensionProfile extensionProfile,                                             String uri, String localName,                                             Attributes attributes)      throws ParseException, IOException {    return new Handler(localName, attributes);  }  /**   * Gets the application attribute.   *   * This attribute should contain the name of the last application that   * modified the entry. This is informative only and should not be relied   * on.   *   * @return application attribute   */  public String getApplication() {    return getTextAttribute(APPLICATION_ATTRIBUTE);  }  /**   * Sets the application attribute.   *   * This attribute should be set every time an entry is inserted   * or updated. It is set automatically by   * {@link GoogleBaseService#update(java.net.URL,   *   com.google.gdata.data.BaseEntry)}   * {@link GoogleBaseService#insert(java.net.URL,   *   com.google.gdata.data.BaseEntry)} and   * {@link GoogleBaseService#batch(java.net.URL,   *   com.google.gdata.data.BaseFeed)}.   *   * @param name   */  public void setApplication(String name) {    removeAttributes(APPLICATION_ATTRIBUTE, GoogleBaseAttributeType.TEXT);    addTextAttribute(APPLICATION_ATTRIBUTE, name);  }  /**   * Private handler for one XML tag that creates and adds   * an {@link com.google.api.gbase.client.GoogleBaseAttribute} into the list.   *   */  private class Handler extends XmlParser.ElementHandler {    /*    * This handler supposes that all tags in the namespace look like this:    *    * <x:tag_name [type='...']>...text...</x:tag_name>    *    * or like this:    *    * <x:tag_name [type='...']>    *   <x:subtag1>...text...</x:subtag1>    *   <x:subtag2>...text...</x:subtag2>    *    ...    * </x:tag_name> (with all sub tags appearing at most once)    *    * Anything else will be ignored.    */    private final GoogleBaseAttribute attribute;    Handler(String localName, Attributes xmlAttributes) {      String attributeName = convertToAttributeName(localName);      this.attribute = createExtensionAttribute(attributeName, xmlAttributes);      attributes.add(attribute);    }    @Override    public void processEndElement() throws ParseException {      if (super.value != null) {        attribute.setValue(super.value);      }    }    @Override    public XmlParser.ElementHandler getChildHandler(final String uri,                                                     final String localName,                                                     Attributes attrs) {      return new XmlParser.ElementHandler() {        private int width = -1;        private int height = -1;               @Override        public void processEndElement() {          if (GoogleBaseNamespaces.GM_URI.equals(uri)) {            if (GM_ADJUSTED_VALUE_ATTRIBUTE.equals(localName)) {              attribute.getAdjustments().setValue(super.value);            } else if (GM_ADJUSTED_NAME_ATTRIBUTE.equals(localName)) {              attribute.getAdjustments().setName(super.value);                          } else if (GM_THUMBNAIL_ATTRIBUTE.equals(localName)) {              Thumbnail thumbnail = new Thumbnail();              thumbnail.setUrl(super.value.trim());              if ((width > 0) && (height > 0)) {                thumbnail.setSize(width, height);              }              attribute.getThumbnails().add(thumbnail);            }            // if the uri is gm but the name is not recognized, we ignore it          } else {            // only non-gm uris are considered sub-elements            attribute.setSubElement(localName, super.value);          }        }                @Override        public void processAttribute(String namespace, String localName,            String value) throws ParseException {          if ("width".equals(localName)) {            width = parseInteger(value);          } else if ("height".equals(localName)) {            height = parseInteger(value);          }        }                private int parseInteger(String value) throws ParseException {          try {            return Integer.parseInt(value);          } catch (NumberFormatException nfe) {            throw new ParseException(                "Invalid size value '" + value + "'", nfe);          }        }      };            }  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -