parse json and get attributes with rest controller java - jhipster

I have this code, the entity is persistable I want to make it non persistable so I parse json file and get name and icon values and display them instead of getting this values from database so that is why I want to change this code
/**
* A Pcomponent.
*/
#Entity
#Table(name = "pcomponent")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Pcomponent implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "icon")
private String icon;
#Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public Pcomponent icon(String icon) {
this.icon = icon;
return this;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public Pcomponent name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pcomponent pcomponent = (Pcomponent) o;
if (pcomponent.id == null || id == null) {
return false;
}
return Objects.equals(id, pcomponent.id);
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "Pcomponent{" +
"id=" + id +
", icon='" + icon + "'" +
", name='" + name + "'" +
'}';
}
}
/**
* Spring Data JPA repository for the Pcomponent entity.
*/
public interface PcomponentRepository extends
JpaRepository<Pcomponent,Long> {
}
/**
* A DTO for the Pcomponent entity.
*/
public class PcomponentDTO implements Serializable {
private Long id;
private String icon;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PcomponentDTO pcomponentDTO = (PcomponentDTO) o;
if ( ! Objects.equals(id, pcomponentDTO.id)) {
return false;
}
return true;
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "PcomponentDTO{" +
"id=" + id +
", icon='" + icon + "'" +
", name='" + name + "'" +
'}';
}
}
/**
* Mapper for the entity Pcomponent and its DTO PcomponentDTO.
*/
#Mapper(componentModel = "spring", uses = {})
public interface PcomponentMapper {
PcomponentDTO pcomponentToPcomponentDTO(Pcomponent pcomponent);
List<PcomponentDTO> pcomponentsToPcomponentDTOs(List<Pcomponent> pcomponents);
Pcomponent pcomponentDTOToPcomponent(PcomponentDTO pcomponentDTO);
List<Pcomponent> pcomponentDTOsToPcomponents(List<PcomponentDTO> pcomponentDTOs);
/**
* generating the fromId for all mappers if the databaseType is sql, as the class has relationship to it might need it, instead of
* creating a new attribute to know if the entity has any relationship from some other entity
*
* #param id id of the entity
* #return the entity instance
*/
default Pcomponent pcomponentFromId(Long id) {
if (id == null) {
return null;
}
Pcomponent pcomponent = new Pcomponent();
pcomponent.setId(id);
return pcomponent;
}
}
/**
* Service Implementation for managing Pcomponent.
*/
#Service
#Transactional
public class PcomponentService {
private final Logger log =
LoggerFactory.getLogger(PcomponentService.class);
private final PcomponentRepository pcomponentRepository;
private final PcomponentMapper pcomponentMapper;
public PcomponentService(PcomponentRepository pcomponentRepository, PcomponentMapper pcomponentMapper) {
this.pcomponentRepository = pcomponentRepository;
this.pcomponentMapper = pcomponentMapper;
}
/**
* Save a pcomponent.
*
* #param pcomponentDTO the entity to save
* #return the persisted entity
*/
public PcomponentDTO save(PcomponentDTO pcomponentDTO) {
log.debug("Request to save Pcomponent : {}", pcomponentDTO);
Pcomponent pcomponent = pcomponentMapper.pcomponentDTOToPcomponent(pcomponentDTO);
pcomponent = pcomponentRepository.save(pcomponent);
PcomponentDTO result = pcomponentMapper.pcomponentToPcomponentDTO(pcomponent);
return result;
}
/**
* Get all the pcomponents.
*
* #param pageable the pagination information
* #return the list of entities
*/
#Transactional(readOnly = true)
public Page<PcomponentDTO> findAll(Pageable pageable) {
log.debug("Request to get all Pcomponents");
Page<Pcomponent> result = pcomponentRepository.findAll(pageable);
return result.map(pcomponent -> pcomponentMapper.pcomponentToPcomponentDTO(pcomponent));
}
/**
* Get one pcomponent by id.
*
* #param id the id of the entity
* #return the entity
*/
#Transactional(readOnly = true)
public PcomponentDTO findOne(Long id) {
log.debug("Request to get Pcomponent : {}", id);
Pcomponent pcomponent = pcomponentRepository.findOne(id);
PcomponentDTO pcomponentDTO = pcomponentMapper.pcomponentToPcomponentDTO(pcomponent);
return pcomponentDTO;
}
/**
* Delete the pcomponent by id.
*
* #param id the id of the entity
*/
public void delete(Long id) {
log.debug("Request to delete Pcomponent : {}", id);
pcomponentRepository.delete(id);
}
}
/**
* REST controller for managing Pcomponent.
*/
#RestController
#RequestMapping("/api")
public class PcomponentResource {
private final Logger log =
LoggerFactory.getLogger(PcomponentResource.class);
private static final String ENTITY_NAME = "pcomponent";
private final PcomponentService pcomponentService;
public PcomponentResource(PcomponentService pcomponentService) {
this.pcomponentService = pcomponentService;
}
/**
* POST /pcomponents : Create a new pcomponent.
*
* #param pcomponentDTO the pcomponentDTO to create
* #return the ResponseEntity with status 201 (Created) and with body the new pcomponentDTO, or with status 400 (Bad Request) if the pcomponent has already an ID
* #throws URISyntaxException if the Location URI syntax is incorrect
*/
#PostMapping("/pcomponents")
#Timed
public ResponseEntity<PcomponentDTO> createPcomponent(#RequestBody PcomponentDTO pcomponentDTO) throws URISyntaxException {
log.debug("REST request to save Pcomponent : {}", pcomponentDTO);
if (pcomponentDTO.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new pcomponent cannot already have an ID")).body(null);
}
PcomponentDTO result = pcomponentService.save(pcomponentDTO);
return ResponseEntity.created(new URI("/api/pcomponents/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /pcomponents : Updates an existing pcomponent.
*
* #param pcomponentDTO the pcomponentDTO to update
* #return the ResponseEntity with status 200 (OK) and with body the updated pcomponentDTO,
* or with status 400 (Bad Request) if the pcomponentDTO is not valid,
* or with status 500 (Internal Server Error) if the pcomponentDTO couldnt be updated
* #throws URISyntaxException if the Location URI syntax is incorrect
*/
#PutMapping("/pcomponents")
#Timed
public ResponseEntity<PcomponentDTO> updatePcomponent(#RequestBody PcomponentDTO pcomponentDTO) throws URISyntaxException {
log.debug("REST request to update Pcomponent : {}", pcomponentDTO);
if (pcomponentDTO.getId() == null) {
return createPcomponent(pcomponentDTO);
}
PcomponentDTO result = pcomponentService.save(pcomponentDTO);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, pcomponentDTO.getId().toString()))
.body(result);
}
/**
* GET /pcomponents : get all the pcomponents.
*
* #param pageable the pagination information
* #return the ResponseEntity with status 200 (OK) and the list of pcomponents in body
*/
#GetMapping("/pcomponents")
#Timed
public ResponseEntity<List<PcomponentDTO>> getAllPcomponents(#ApiParam Pageable pageable) {
log.debug("REST request to get a page of Pcomponents");
Page<PcomponentDTO> page = pcomponentService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/pcomponents");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* GET /pcomponents/:id : get the "id" pcomponent.
*
* #param id the id of the pcomponentDTO to retrieve
* #return the ResponseEntity with status 200 (OK) and with body the pcomponentDTO, or with status 404 (Not Found)
*/
#GetMapping("/pcomponents/{id}")
#Timed
public ResponseEntity<PcomponentDTO> getPcomponent(#PathVariable Long id) {
log.debug("REST request to get Pcomponent : {}", id);
PcomponentDTO pcomponentDTO = pcomponentService.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(pcomponentDTO));
}
/**
* DELETE /pcomponents/:id : delete the "id" pcomponent.
*
* #param id the id of the pcomponentDTO to delete
* #return the ResponseEntity with status 200 (OK)
*/
#DeleteMapping("/pcomponents/{id}")
#Timed
public ResponseEntity<Void> deletePcomponent(#PathVariable Long id) {
log.debug("REST request to delete Pcomponent : {}", id);
pcomponentService.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
}

Related

How to access saved entity via metadata using parameters in the route

I have an entity contact
<?php
namespace App\Entity;
use App\Repository\ContactRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=ContactRepository::class)
*/
class Contact
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=50)
*/
private $firstName;
/**
* #ORM\Column(type="string", length=50)
*/
private $lastName;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dob;
/**
* #ORM\Column(type="string", length=50)
*/
private $email;
/**
* #ORM\Column(type="string", length=15)
*/
private $phone;
public function getId(): ?int
{
return $this->id;
}
public function getFirstName(): ?string
{
return $this->firstName;
}
public function setFirstName(string $firstName): self
{
$this->firstName = $firstName;
return $this;
}
public function getLastName(): ?string
{
return $this->lastName;
}
public function setLastName(string $lastName): self
{
$this->lastName = $lastName;
return $this;
}
public function getDob(): ?\DateTimeInterface
{
return $this->dob;
}
public function setDob(?\DateTimeInterface $dob): self
{
$this->dob = $dob;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getPhone(): ?string
{
return $this->phone;
}
public function setPhone(string $phone): self
{
$this->phone = $phone;
return $this;
}
}
I want to select one (or more) contact with this URL: /c00210/readallbyparam/{routeProperty}/{routeValue}
For example: /c00210/readallbyparam/lastname/Mendelsohn
This should return 2 records:
Felix Mendelsohn
Fanny Mendelsohn
How do I write the render() function?
How do I write the twig instructions?
I suppose I should use the metadata, but I don't know
+++++++++++++++++++++++++++++++++++++++
here is the function in my controller
/**
* #Route("/c00210/readallbyparam/{routeProperty}/{routeValue}", name="c00210_read_all_by_param")
*/
public function findAllByparam( $routeProperty,$routeValue)
{
$property = $routeProperty;
$value = $routeValue;
$repository = $this->getDoctrine()->getRepository(Contact::class);
$contacts = $repository->findAll();
return $this->render('c00210/readbycriteria2.html.twig', [
'function' => 'find(<id>)',
'description' => 'finds the with the given Id',
'property' => $property,
'value' => $value,
'contacts' => $contacts,
]);
routeProperty should be a column name, and routeValue a column value
shoud be equivalent to
SELECT * FROM contacts WHERE lastname = 'Mendelsohn'

CustomHTMLTagProcessor for iTextSharp

I have the following code;
Dim sr As StreamReader = New StreamReader("C:\\temp\\test.htm")
Dim line As String
line = sr.ReadToEnd
sr.Close()
Dim fsNew As New StringReader(line)
Dim Document As New Document()
Using fs As New FileStream("C:\\temp\\test.pdf", FileMode.Create)
PdfWriter.GetInstance(Document, fs)
Using stringReader As New StringReader(line)
Dim parsedList As List(Of IElement) = HTMLWorker.ParseToList(stringReader, Nothing)
Document.Open()
For Each item As Object In parsedList
Document.Add(DirectCast(item, IElement))
Next
Document.Close()
End Using
End Using
Document.Close()
I am trying to fix the problem with embedded base64 images that is referenced here. I created the CustomImageHTMLTagProcessor which is using the IHTMLTagProcessor interface, but when it came time to modify the HTMLWorker class, I wasn't sure what to change. This is the HTMLWorker class.
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.util;
using iTextSharp.text;
using iTextSharp.text.log;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.draw;
using iTextSharp.text.xml.simpleparser;
namespace iTextSharp.text.html.simpleparser {
[Obsolete]
public class HTMLWorker : ISimpleXMLDocHandler, IDocListener {
private static readonly ILogger LOGGER = LoggerFactory.GetLogger(typeof(HTMLWorker));
protected IDocListener document;
protected internal IDictionary<String, IHTMLTagProcessor> tags;
public HTMLWorker(IDocListener document) : this(document, null, null) {
}
public HTMLWorker(IDocListener document, IDictionary<String, IHTMLTagProcessor> tags, StyleSheet style) {
this.document = document;
SetSupportedTags(tags);
SetStyleSheet(style);
}
virtual public void SetSupportedTags(IDictionary<String, IHTMLTagProcessor> tags) {
if (tags == null)
tags = new HTMLTagProcessors();
this.tags = tags;
}
virtual public void SetStyleSheet(StyleSheet style) {
if (style == null)
style = new StyleSheet();
this.style = style;
}
virtual public void Parse(TextReader reader) {
LOGGER.Info("Please note, there is a more extended version of the HTMLWorker available in the iText XMLWorker");
SimpleXMLParser.Parse(this, null, reader, true);
}
// state machine
protected Stack<IElement> stack = new Stack<IElement>();
protected Paragraph currentParagraph;
private ChainedProperties chain = new ChainedProperties();
public virtual void StartDocument() {
Dictionary<String, String> attrs = new Dictionary<String, String>();
style.ApplyStyle(HtmlTags.BODY, attrs);
chain.AddToChain(HtmlTags.BODY, attrs);
}
public virtual void StartElement(String tag, IDictionary<String, String> attrs) {
IHTMLTagProcessor htmlTag;
tags.TryGetValue(tag, out htmlTag);
if (htmlTag == null) {
return;
}
style.ApplyStyle(tag, attrs);
StyleSheet.ResolveStyleAttribute(attrs, chain);
htmlTag.StartElement(this, tag, attrs);
}
public virtual void Text(String content) {
if (skipText)
return;
if (currentParagraph == null) {
currentParagraph = CreateParagraph();
}
if (!insidePRE) {
// newlines and carriage returns are ignored
if (content.Trim().Length == 0 && content.IndexOf(' ') < 0) {
return;
}
content = HtmlUtilities.EliminateWhiteSpace(content);
}
Chunk chunk = CreateChunk(content);
currentParagraph.Add(chunk);
}
public virtual void EndElement(String tag) {
IHTMLTagProcessor htmlTag;
tags.TryGetValue(tag, out htmlTag);
if (htmlTag == null) {
return;
}
// process the tag
htmlTag.EndElement(this, tag);
}
public virtual void EndDocument() {
// flush the stack
foreach (IElement e in stack)
document.Add(e);
// add current paragraph
if (currentParagraph != null)
document.Add(currentParagraph);
currentParagraph = null;
}
virtual public void NewLine() {
if (currentParagraph == null) {
currentParagraph = new Paragraph();
}
currentParagraph.Add(CreateChunk("\n"));
}
virtual public void CarriageReturn() {
if (currentParagraph == null)
return;
if (stack.Count == 0)
document.Add(currentParagraph);
else {
IElement obj = stack.Pop();
if (obj is ITextElementArray) {
ITextElementArray current = (ITextElementArray) obj;
current.Add(currentParagraph);
}
stack.Push(obj);
}
currentParagraph = null;
}
/**
* Stacks the current paragraph, indicating that we're starting
* a new span.
* #since 5.0.6
*/
virtual public void FlushContent() {
PushToStack(currentParagraph);
currentParagraph = new Paragraph();
}
/**
* Pushes an element to the Stack.
* #param element
* #since 5.0.6
*/
virtual public void PushToStack(IElement element) {
if (element != null)
stack.Push(element);
}
/**
* Updates the chain with a new tag and new attributes.
* #param tag the new tag
* #param attrs the corresponding attributes
* #since 5.0.6
*/
virtual public void UpdateChain(String tag, IDictionary<String, String> attrs) {
chain.AddToChain(tag, attrs);
}
/**
* Updates the chain by removing a tag.
* #param tag the new tag
* #since 5.0.6
*/
virtual public void UpdateChain(String tag) {
chain.RemoveChain(tag);
}
// providers that help find resources such as images and fonts
/**
* Key used to store the image provider in the providers map.
* #since 5.0.6
*/
public const String IMG_PROVIDER = "img_provider";
/**
* Key used to store the image processor in the providers map.
* #since 5.0.6
*/
public const String IMG_PROCESSOR = "img_interface";
/**
* Key used to store the image store in the providers map.
* #since 5.0.6
*/
public const String IMG_STORE = "img_static";
/**
* Key used to store the image baseurl provider in the providers map.
* #since 5.0.6
*/
public const String IMG_BASEURL = "img_baseurl";
/**
* Key used to store the font provider in the providers map.
* #since 5.0.6
*/
public const String FONT_PROVIDER = "font_factory";
/**
* Key used to store the link provider in the providers map.
* #since 5.0.6
*/
public const String LINK_PROVIDER = "alink_interface";
/**
* IDictionary containing providers such as a FontProvider or ImageProvider.
* #since 5.0.6 (renamed from interfaceProps)
*/
private IDictionary<String, Object> providers = new Dictionary<String, Object>();
/**
* Setter for the providers.
* If a FontProvider is added, the ElementFactory is updated.
* #param providers a IDictionary with different providers
* #since 5.0.6
*/
virtual public void SetProviders(IDictionary<String, Object> providers) {
if (providers == null)
return;
this.providers = providers;
IFontProvider ff = null;
if (providers.ContainsKey(FONT_PROVIDER))
ff = (IFontProvider)providers[FONT_PROVIDER];
if (ff != null)
factory.FontProvider = ff;
}
// factory that helps create objects
/**
* Factory that is able to create iText Element objects.
* #since 5.0.6
*/
private ElementFactory factory = new ElementFactory();
/**
* Creates a Chunk using the factory.
* #param content the content of the chunk
* #return a Chunk with content
* #since 5.0.6
*/
virtual public Chunk CreateChunk(String content) {
return factory.CreateChunk(content, chain);
}
/**
* Creates a Paragraph using the factory.
* #return a Paragraph without any content
* #since 5.0.6
*/
virtual public Paragraph CreateParagraph() {
return factory.CreateParagraph(chain);
}
/**
* Creates a List object.
* #param tag should be "ol" or "ul"
* #return a List object
* #since 5.0.6
*/
virtual public List CreateList(String tag) {
return factory.CreateList(tag, chain);
}
/**
* Creates a ListItem object.
* #return a ListItem object
* #since 5.0.6
*/
virtual public ListItem CreateListItem() {
return factory.CreateListItem(chain);
}
/**
* Creates a LineSeparator object.
* #param attrs properties of the LineSeparator
* #return a LineSeparator object
* #since 5.0.6
*/
virtual public LineSeparator CreateLineSeparator(IDictionary<String, String> attrs) {
return factory.CreateLineSeparator(attrs, currentParagraph.Leading / 2);
}
/**
* Creates an Image object.
* #param attrs properties of the Image
* #return an Image object (or null if the Image couldn't be found)
* #throws DocumentException
* #throws IOException
* #since 5.0.6
*/
virtual public Image CreateImage(IDictionary<String, String> attrs) {
String src;
attrs.TryGetValue(HtmlTags.SRC, out src);
if (src == null)
return null;
Image img = factory.CreateImage(
src, attrs, chain, document,
providers.ContainsKey(IMG_PROVIDER) ? (IImageProvider)providers[IMG_PROVIDER] : null,
providers.ContainsKey(IMG_STORE) ? (ImageStore)providers[IMG_STORE] : null,
providers.ContainsKey(IMG_BASEURL) ? (string)providers[IMG_BASEURL] : null);
return img;
}
/**
* Creates a Cell.
* #param tag the tag
* #return a CellWrapper object
* #since 5.0.6
*/
virtual public CellWrapper CreateCell(String tag) {
return new CellWrapper(tag, chain);
}
// processing objects
/**
* Adds a link to the current paragraph.
* #since 5.0.6
*/
virtual public void ProcessLink() {
if (currentParagraph == null) {
currentParagraph = new Paragraph();
}
// The link provider allows you to do additional processing
ILinkProcessor i = null;
if (providers.ContainsKey(LINK_PROVIDER))
i = (ILinkProcessor) providers[LINK_PROVIDER];
if (i == null || !i.Process(currentParagraph, chain)) {
// sets an Anchor for all the Chunks in the current paragraph
String href = chain[HtmlTags.HREF];
if (href != null) {
foreach (Chunk ck in currentParagraph.Chunks) {
ck.SetAnchor(href);
}
}
}
// a link should be added to the current paragraph as a phrase
if (stack.Count == 0) {
// no paragraph to add too, 'a' tag is first element
Paragraph tmp = new Paragraph(new Phrase(currentParagraph));
currentParagraph = tmp;
} else {
Paragraph tmp = (Paragraph) stack.Pop();
tmp.Add(new Phrase(currentParagraph));
currentParagraph = tmp;
}
}
/**
* Fetches the List from the Stack and adds it to
* the TextElementArray on top of the Stack,
* or to the Document if the Stack is empty.
* #throws DocumentException
* #since 5.0.6
*/
virtual public void ProcessList() {
if (stack.Count == 0)
return;
IElement obj = stack.Pop();
if (!(obj is List)) {
stack.Push(obj);
return;
}
if (stack.Count == 0)
document.Add(obj);
else
((ITextElementArray) stack.Peek()).Add(obj);
}
/**
* Looks for the List object on the Stack,
* and adds the ListItem to the List.
* #throws DocumentException
* #since 5.0.6
*/
virtual public void ProcessListItem() {
if (stack.Count == 0)
return;
IElement obj = stack.Pop();
if (!(obj is ListItem)) {
stack.Push(obj);
return;
}
if (stack.Count == 0) {
document.Add(obj);
return;
}
ListItem item = (ListItem) obj;
IElement list = stack.Pop();
if (!(list is List)) {
stack.Push(list);
return;
}
((List) list).Add(item);
item.AdjustListSymbolFont();
stack.Push(list);
}
/**
* Processes an Image.
* #param img
* #param attrs
* #throws DocumentException
* #since 5.0.6
*/
virtual public void ProcessImage(Image img, IDictionary<String, String> attrs) {
IImageProcessor processor = null;
if (providers.ContainsKey(IMG_PROCESSOR))
processor = (IImageProcessor)providers[IMG_PROCESSOR];
if (processor == null || !processor.Process(img, attrs, chain, document)) {
String align;
attrs.TryGetValue(HtmlTags.ALIGN, out align);
if (align != null) {
CarriageReturn();
}
if (currentParagraph == null) {
currentParagraph = CreateParagraph();
}
currentParagraph.Add(new Chunk(img, 0, 0, true));
currentParagraph.Alignment = HtmlUtilities.AlignmentValue(align);
if (align != null) {
CarriageReturn();
}
}
}
/**
* Processes the Table.
* #throws DocumentException
* #since 5.0.6
*/
virtual public void ProcessTable() {
TableWrapper table = (TableWrapper) stack.Pop();
PdfPTable tb = table.CreateTable();
tb.SplitRows = true;
if (stack.Count == 0)
document.Add(tb);
else
((ITextElementArray) stack.Peek()).Add(tb);
}
/**
* Gets the TableWrapper from the Stack and adds a new row.
* #since 5.0.6
*/
virtual public void ProcessRow() {
List<PdfPCell> row = new List<PdfPCell>();
List<float> cellWidths = new List<float>();
bool percentage = false;
float width;
float totalWidth = 0;
int zeroWidth = 0;
TableWrapper table = null;
while (true) {
IElement obj = stack.Pop();
if (obj is CellWrapper) {
CellWrapper cell = (CellWrapper)obj;
width = cell.Width;
cellWidths.Add(width);
percentage |= cell.IsPercentage;
if (width == 0) {
zeroWidth++;
}
else {
totalWidth += width;
}
row.Add(cell.Cell);
}
if (obj is TableWrapper) {
table = (TableWrapper) obj;
break;
}
}
table.AddRow(row);
if (cellWidths.Count > 0) {
// cells come off the stack in reverse, naturally
totalWidth = 100 - totalWidth;
cellWidths.Reverse();
float[] widths = new float[cellWidths.Count];
bool hasZero = false;
for (int i = 0; i < widths.Length; i++) {
widths[i] = cellWidths[i];
if (widths[i] == 0 && percentage && zeroWidth > 0) {
widths[i] = totalWidth / zeroWidth;
}
if (widths[i] == 0) {
hasZero = true;
break;
}
}
if (!hasZero)
table.ColWidths = widths;
}
stack.Push(table);
}
// state variables and methods
/** Stack to keep track of table tags. */
private Stack<bool[]> tableState = new Stack<bool[]>();
/** Boolean to keep track of TR tags. */
private bool pendingTR = false;
/** Boolean to keep track of TD and TH tags */
private bool pendingTD = false;
/** Boolean to keep track of LI tags */
private bool pendingLI = false;
/**
* Boolean to keep track of PRE tags
* #since 5.0.6 renamed from isPRE
*/
private bool insidePRE = false;
/**
* Indicates if text needs to be skipped.
* #since iText 5.0.6 (private => protected)
*/
protected internal bool skipText = false;
/**
* Pushes the values of pendingTR and pendingTD
* to a state stack.
* #since 5.0.6
*/
virtual public void PushTableState() {
tableState.Push(new bool[] { pendingTR, pendingTD });
}
/**
* Pops the values of pendingTR and pendingTD
* from a state stack.
* #since 5.0.6
*/
virtual public void PopTableState() {
bool[] state = tableState.Pop();
pendingTR = state[0];
pendingTD = state[1];
}
/**
* #return the pendingTR
* #since 5.0.6
*/
virtual public bool IsPendingTR() {
return pendingTR;
}
/**
* #param pendingTR the pendingTR to set
* #since 5.0.6
*/
virtual public void SetPendingTR(bool pendingTR) {
this.pendingTR = pendingTR;
}
/**
* #return the pendingTD
* #since 5.0.6
*/
virtual public bool IsPendingTD() {
return pendingTD;
}
/**
* #param pendingTD the pendingTD to set
* #since 5.0.6
*/
virtual public void SetPendingTD(bool pendingTD) {
this.pendingTD = pendingTD;
}
/**
* #return the pendingLI
* #since 5.0.6
*/
virtual public bool IsPendingLI() {
return pendingLI;
}
/**
* #param pendingLI the pendingLI to set
* #since 5.0.6
*/
virtual public void SetPendingLI(bool pendingLI) {
this.pendingLI = pendingLI;
}
/**
* #return the insidePRE
* #since 5.0.6
*/
virtual public bool IsInsidePRE() {
return insidePRE;
}
/**
* #param insidePRE the insidePRE to set
* #since 5.0.6
*/
virtual public void SetInsidePRE(bool insidePRE) {
this.insidePRE = insidePRE;
}
/**
* #return the skipText
* #since 5.0.6
*/
virtual public bool IsSkipText() {
return skipText;
}
/**
* #param skipText the skipText to set
* #since 5.0.6
*/
virtual public void SetSkipText(bool skipText) {
this.skipText = skipText;
}
// static methods to parse HTML to a List of Element objects.
/** The resulting list of elements. */
protected List<IElement> objectList;
/**
* Parses an HTML source to a List of Element objects
* #param reader the HTML source
* #param style a StyleSheet object
* #return a List of Element objects
* #throws IOException
*/
public static List<IElement> ParseToList(TextReader reader, StyleSheet style) {
return ParseToList(reader, style, null);
}
/**
* Parses an HTML source to a List of Element objects
* #param reader the HTML source
* #param style a StyleSheet object
* #param providers map containing classes with extra info
* #return a List of Element objects
* #throws IOException
*/
public static List<IElement> ParseToList(TextReader reader, StyleSheet style,
Dictionary<String, Object> providers) {
return ParseToList(reader, style, null, providers);
}
/**
* Parses an HTML source to a List of Element objects
* #param reader the HTML source
* #param style a StyleSheet object
* #param tags a map containing supported tags and their processors
* #param providers map containing classes with extra info
* #return a List of Element objects
* #throws IOException
* #since 5.0.6
*/
public static List<IElement> ParseToList(TextReader reader, StyleSheet style,
IDictionary<String, IHTMLTagProcessor> tags, Dictionary<String, Object> providers) {
HTMLWorker worker = new HTMLWorker(null, tags, style);
worker.document = worker;
worker.SetProviders(providers);
worker.objectList = new List<IElement>();
worker.Parse(reader);
return worker.objectList;
}
// DocListener interface
/**
* #see com.itextpdf.text.ElementListener#add(com.itextpdf.text.Element)
*/
virtual public bool Add(IElement element) {
objectList.Add(element);
return true;
}
/**
* #see com.itextpdf.text.DocListener#close()
*/
virtual public void Close() {
}
/**
* #see com.itextpdf.text.DocListener#newPage()
*/
virtual public bool NewPage() {
return true;
}
/**
* #see com.itextpdf.text.DocListener#open()
*/
virtual public void Open() {
}
/**
* #see com.itextpdf.text.DocListener#resetPageCount()
*/
virtual public void ResetPageCount() {
}
/**
* #see com.itextpdf.text.DocListener#setMarginMirroring(bool)
*/
virtual public bool SetMarginMirroring(bool marginMirroring) {
return false;
}
/**
* #see com.itextpdf.text.DocListener#setMarginMirroring(bool)
* #since 2.1.6
*/
virtual public bool SetMarginMirroringTopBottom(bool marginMirroring) {
return false;
}
/**
* #see com.itextpdf.text.DocListener#setMargins(float, float, float, float)
*/
virtual public bool SetMargins(float marginLeft, float marginRight,
float marginTop, float marginBottom) {
return true;
}
/**
* #see com.itextpdf.text.DocListener#setPageCount(int)
*/
virtual public int PageCount {
set {
}
}
/**
* #see com.itextpdf.text.DocListener#setPageSize(com.itextpdf.text.Rectangle)
*/
virtual public bool SetPageSize(Rectangle pageSize) {
return true;
}
// deprecated methods
/**
* Sets the providers.
* #deprecated use SetProviders() instead
*/
virtual public void SetInterfaceProps(Dictionary<String, Object> providers) {
SetProviders(providers);
}
/**
* Gets the providers
* #deprecated use GetProviders() instead
*/
virtual public IDictionary<String, Object> GetInterfaceProps() {
return providers;
}
public virtual void Dispose() {
Close();
}
}
}
As Chris Haas Mentioned HtmlWorker is Deprecated. XmlWorker is the new way to convert HTML to PDF.

Why Cassandra throwing com.datastax.driver.core.exceptions.InvalidQueryException: Multiple definitions found for column

Context:
I am running a jUnit test in eclipse by using embedded Cassandra to test my DAO class which is using an Astyanax client configured for JavaDriver. When DAO object instance insert into Cassandra I am getting this exception com.datastax.driver.core.exceptions.InvalidQueryException: Multiple definitions found for column ..columnname
TestClass
public class LeaderBoardDaoTest {
private static LeaderBoardDao dao;
public static CassandraCQLUnit cassandraCQLUnit;
private String hostIp = "127.0.0.1";
private int port = 9142;
public Session session;
public Cluster cluster;
#BeforeClass
public static void startCassandra() throws IOException, TTransportException, ConfigurationException, InterruptedException {
System.setProperty("archaius.deployment.applicationId", "leaderboardapi");
System.setProperty("archaius.deployment.environment", "test");
EmbeddedCassandraServerHelper.startEmbeddedCassandra("cassandra.yaml");
// cassandraCQLUnit = new CassandraCQLUnit(new
// ClassPathCQLDataSet("simple.cql", "lbapi"), "cassandra.yaml");
Injector injector = Guice.createInjector(new TestModule());
dao = injector.getInstance(LeaderBoardDao.class);
}
#Before
public void load() {
cluster = new Cluster.Builder().withClusterName("leaderboardcassandra").addContactPoints(hostIp).withPort(port).build();
session = cluster.connect();
CQLDataLoader dataLoader = new CQLDataLoader(session);
dataLoader.load(new ClassPathCQLDataSet("simple.cql", "lbapi"));
session = dataLoader.getSession();
}
#Test
public void test() {
ResultSet result = session.execute("select * from mytable WHERE id='myKey01'");
Assert.assertEquals(result.iterator().next().getString("value"), "myValue01");
}
#Test
public void testInsert() {
LeaderBoard lb = new LeaderBoard();
lb.setName("name-1");
lb.setDescription("description-1");
lb.setActivityType(ActivityType.FUEL);
lb.setImage("http:/");
lb.setLbId(UUID.fromString("3F2504E0-4F89-41D3-9A0C-0305E82C3301"));
lb.setStartTime(new Date());
lb.setEndTime(new Date());
dao.insert(lb);
ResultSet resultSet = session.execute("select * from leaderboards WHERE leaderboardid='3F2504E0-4F89-41D3-9A0C-0305E82C3301'");
}
#After
public void clearCassandra() {
EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
}
#AfterClass
public static void stopCassandra() {
EmbeddedCassandraServerHelper.stopEmbeddedCassandra();
}
}
Class under test
#Singleton
public class LeaderBoardDao {
private static final Logger log = LoggerFactory.getLogger(LeaderBoardDao.class);
#Inject
private AstyanaxMutationsJavaDriverClient client;
private static final String END_TIME = "end_time";
private static final String START_TIME = "start_time";
private static final String IMAGE = "image";
private static final String ACTIVITY_TYPE = "activity_type";
private static final String DESCRIPTION = "description";
private static final String NAME = "name";
private static final String LEADERBOARD_ID = "leaderboardID";
private static final String COLUMN_FAMILY_NAME = "leaderboards";
private ColumnFamily<UUID, String> cf;
public LeaderBoardDao() throws ConnectionException {
cf = ColumnFamily.newColumnFamily(COLUMN_FAMILY_NAME, UUIDSerializer.get(), StringSerializer.get());
}
/**
* Writes the Leaderboard to the database.
*
* #param lb
*/
public void insert(LeaderBoard lb) {
try {
MutationBatch m = client.getKeyspace().prepareMutationBatch();
cf.describe(client.getKeyspace());
m.withRow(cf, lb.getLbId()).putColumn(LEADERBOARD_ID, UUIDUtil.asByteArray(lb.getLbId()), null).putColumn(NAME, lb.getName(), null).putColumn(DESCRIPTION, lb.getDescription(), null)
.putColumn(ACTIVITY_TYPE, lb.getActivityType().name(), null).putColumn(IMAGE, lb.getImage()).putColumn(START_TIME, lb.getStartTime()).putColumn(END_TIME, lb.getEndTime());
m.execute();
} catch (ConnectionException e) {
Throwables.propagate(e);
}
}
/**
* Reads leaderboard from database
*
* #param id
* #return {#link LeaderBoard}
*/
public LeaderBoard read(UUID id) {
OperationResult<ColumnList<String>> result;
LeaderBoard lb = null;
try {
result = client.getKeyspace().prepareQuery(cf).getKey(id).execute();
ColumnList<String> cols = result.getResult();
if (!cols.isEmpty()) {
lb = new LeaderBoard();
lb.setLbId(cols.getUUIDValue(LEADERBOARD_ID, null));
lb.setName(cols.getStringValue(NAME, null));
lb.setActivityType(ActivityType.valueOf(cols.getStringValue(ACTIVITY_TYPE, null)));
lb.setDescription(cols.getStringValue(DESCRIPTION, null));
lb.setEndTime(cols.getDateValue(END_TIME, null));
lb.setStartTime(cols.getDateValue(START_TIME, null));
lb.setImage(cols.getStringValue(IMAGE, null));
} else {
log.warn("read: is empty: no record found for " + id);
}
return lb;
} catch (ConnectionException e) {
log.error("failed to read from C*", e);
throw new RuntimeException("failed to read from C*", e);
}
}
}
When the Java driver throws an InvalidQueryException, it's rethrowing an error from Cassandra. The error "Multiple definitions found for column..." indicates that a column is mentioned more than once in an update statement. You can simulate it in cqlsh:
cqlsh> create table test(i int primary key);
cqlsh> insert into test (i, i) values (1, 2);
code=2200 [Invalid query] message="Multiple definitions found for column i"
I'm not familiar with Astyanax, but my guess is that it already adds the id to the query when you call withRow, so you don't need to add it again with putColumn. Try removing that call (second line in reformatted sample below):
m.withRow(cf, lb.getLbId())
.putColumn(LEADERBOARD_ID, UUIDUtil.asByteArray(lb.getLbId()), null)
... // other putColumn calls

java.lang.ClassCastException: com.rdb.entities.TblStaff cannot be cast to com.rdb.beans.UserManagedBean

I got some isses when try to use a login filter for my JSF, PrimeFaces web application.
Here is the stacktrace:
WARNING: StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.lang.ClassCastException: com.rdb.entities.TblStaff cannot be cast to com.rdb.beans.UserManagedBean
at com.rdb.filter.AuthorizationFilter.doFilter(AuthorizationFilter.java:50)
AuthorizationFilter class:
public class AuthorizationFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
UserManagedBean auth = (UserManagedBean) req.getSession().getAttribute("staff");
if (auth != null && auth.isLoggedIn()) {
chain.doFilter(request, response);
} else {
HttpServletResponse res = (HttpServletResponse) response;
res.sendRedirect(req.getContextPath() + "/frontend/login.xhtml?faces-redirect=true");
}
}
}
My LoginBean
#ManagedBean
#SessionScoped
public class UserManagedBean extends TblStaff implements Serializable {
private TblStaff staff = null;
private String currentLogin;
private String username;
private String password;
private boolean loggedIn;
private ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
#ManagedProperty(value="#{navigationBean}")
private NavigationBean navigationBean;
/**
* Creates a new instance of UserManagedBean
*
*/
public UserManagedBean() {
super();
}
public String login() {
int isValid = doLogin();
if (isValid == 1) {
StaffBLL staffBLL = new StaffBLL();
staff = staffBLL.getStaffByUsername(username);
setSession("staff", staff);
String destinationUrl = null;
if (staff.getRoleId() == 1) {
loggedIn = true;
setCurrentLogin("admin");
destinationUrl = navigationBean.redirectToBackend();
} else if (staff.getRoleId() == 2) {
loggedIn = true;
setCurrentLogin("manager");
destinationUrl = navigationBean.redirectToManager();
} else if (staff.getRoleId() == 3) {
loggedIn = true;
setCurrentLogin("faculty");
destinationUrl = navigationBean.redirectToFaculty();
}
return destinationUrl;
} else {
return navigationBean.toLogin();
}
}
/**
* Set new session if try to logged in
*
* #param key
* #param value
*/
public static void setSession(String key, Object value) {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
session.setAttribute(key, value);
}
/**
* Get session if logged in
*
* #param key
* #return Session
*/
public static Object getSession(String key) {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
return session.getAttribute(key);
}
public String logout() {
loggedIn = false;
ec.invalidateSession();
setCurrentLogin(null);
return navigationBean.toFrontend();
}
public void logoutAdmin(ActionEvent actionEvent) throws IOException {
loggedIn = false;
ec.invalidateSession();
setCurrentLogin(null);
ec.redirect(ec.getRequestContextPath() + "/frontend/index.xhtml?faces-redirect=true");
}
public int doLogin() {
CallableStatement objCall;
SHAConverter hash = new SHAConverter();
int result = -1;
String[] params = new String[3];
params[0] = username;
params[1] = hash.hashBasic(password);
params[2] = null;
try {
objCall = SQLHelper.execute("procLogin", params);
result = objCall.getInt("Result");
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
return result;
}
#Override
public String getPassword() {
return password;
}
#Override
public void setPassword(String password) {
this.password = password;
}
#Override
public String getUsername() {
return username;
}
#Override
public void setUsername(String username) {
this.username = username;
}
public String getCurrentLogin() {
return currentLogin;
}
public void setCurrentLogin(String currentLogin) {
this.currentLogin = currentLogin;
}
public boolean isLoggedIn() {
return loggedIn;
}
public void setLoggedIn(boolean loggedIn) {
this.loggedIn = loggedIn;
}
public void setNavigationBean(NavigationBean navigationBean) {
this.navigationBean = navigationBean;
}
}
And NavigationBean
#ManagedBean
#SessionScoped
public class NavigationBean implements Serializable {
// private static final long serialVersionUID = 1520318172495977648L;
/**
* Redirect to login page.
*
* #return Login page name.
*/
public String redirectToLogin() {
return "/frontend/login.xhtml?faces-redirect=true";
}
/**
* Go to login page.
*
* #return Login page name.
*/
public String toLogin() {
return "/frontend/login.xhtml";
}
/**
* Redirect to backend.
*
* #return Backend page name.
*/
public String redirectToBackend() {
return "/backend/AdminHome.xhtml?faces-redirect=true";
}
/**
* Go to backend page.
*
* #return Backend page name.
*/
public String toBackend() {
return "/backend/AdminHome.xhtml";
}
/**
* Redirect to faculty.
*
* #return Faculty page name.
*/
public String redirectToFaculty() {
return "/frontend/faculty/index.xhtml?faces-redirect=true";
}
/**
* Go to faculty.
*
* #return Faculty page name.
*/
public String toFaculty() {
return "/frontend/faculty/index.xhtml";
}
/**
* Redirect to manager.
*
* #return Manager page name.
*/
public String redirectToManager() {
return "/frontend/manager/index.xhtml?faces-redirect=true";
}
/**
* Go to manager.
*
* #return Manager page name.
*/
public String toManager() {
return "/frontend/manager/index.xhtml";
}
/**
* Redirect to frontend.
*
* #return Frontend page name.
*/
public String redirectToFrontend() {
return "/frontend/index.xhtml?faces-redirect=true";
}
/**
* Go to frontend page.
*
* #return Frontend page name.
*/
public String toFrontend() {
return "/frontend/index.xhtml";
}
}
The stacktrace told me that I can't cast entities to a bean, but I MUST extend TblStaff in my login bean.
Can anyone give me a solution for this?

jaxb difference bwteen java 7 and java 6

I have a jaxb code which used to work in java 6, but after I update to java 7, it generated xml file differently.
in java 6, the file looks like this:
<ns2:recommendation>
<id>4</id>
<type>ARTICLE</type>
<name>Application-4</name>
<description>Great app called Application-4</description>
<publisher>Medio</publisher>
<category>Productivity</category>
<updated>01062001</updated>
<rating>4.0</rating>
<price>.99</price>
<currency>USD</currency>
<iconURI>http://medio.com</iconURI>
<downloadURI>http://medio.com</downloadURI>
<ns2:extensions>
<ns2:extension ns2:key="Sample">
<ns2:value>Extension</ns2:value>
</ns2:extension>
</ns2:extensions>
<ratingCount>35213614</ratingCount>
<downloadCount>12435854</downloadCount>
</ns2:recommendation>
in java 7, it is:
<ma:recommendation>
<id>3</id>
<type>ARTICLE</type>
<name>Application-3</name>
<description>Great app called Application-3</description>
<publisher>Medio</publisher>
<category>Productivity</category>
<updated>01062001</updated>
<rating>4.0</rating>
<price>.99</price>
<currency>USD</currency>
<iconURI>http://medio.com</iconURI>
<downloadURI>http://medio.com</downloadURI>
<_extensions>
<entry>
<key>Sample</key>
<value>Extension</value>
</entry>
</_extensions>
<ratingCount>35213614</ratingCount>
<downloadCount>12435854</downloadCount>
</ma:recommendation>
the difference is the extensions tag, which maps to a java code that doesn't change. anyone knows how to fix it?
java code for extensions:
#XmlRootElement(namespace = XMLNamespace.URL)
#XmlAccessorType(XmlAccessType.NONE)
#XmlType(namespace = XMLNamespace.URL)
public final class ExtensionMap extends HashMap<String, String> {
/** Serialized version unique identifier. */
private static final long serialVersionUID = -7235844731135521813L;
/**
* Default constructor to support JAXB binding.
*/
public ExtensionMap() {
super();
}
/**
* Default constructor to support JAXB binding.
* #param capacity The expected capacity of the map.
*/
public ExtensionMap(int capacity) {
super(capacity);
}
/**
* The list of wrapped Map entries that are structured for binding to XML
* with JAXB.
*
* #return The list of wrapped Map entries that are structured for binding
* to XML with JAXB.
*/
#XmlElement(name = "extension", namespace = XMLNamespace.URL, required = false)
#SuppressWarnings("unused")
private List<ExtensionMapElement> getEntries() {
return new ListAdapter();
}
/**
* The list of wrapped Map entries that are structured for binding to XML
* with JAXB.
*
* #param entries The list of wrapped Map entries that are structured for binding
* to XML with JAXB.
*/
#SuppressWarnings("unused")
private void setEntries(List<ExtensionMapElement> entries) {
if (entries != null) {
for (ExtensionMapElement entry : entries) {
put(entry.getKey(), entry.getValue());
}
}
}
/**
* Adapter for the list collection.
*
*/
private class ListAdapter implements List<ExtensionMapElement> {
#Override
public boolean add(ExtensionMapElement e) {
put(e.getKey(), e.getValue());
return true;
}
#Override
public void add(int index, ExtensionMapElement element) {
add(element);
}
#Override
public boolean addAll(Collection<? extends ExtensionMapElement> c) {
if (c != null) {
for (ExtensionMapElement element : c) {
add(element);
}
}
return true;
}
#Override
public boolean addAll(int index, Collection<? extends ExtensionMapElement> c) {
addAll(c);
return true;
}
#Override
public void clear() {
ExtensionMap.this.clear();
}
#Override
public boolean contains(Object o) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public boolean containsAll(Collection<?> c) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public ExtensionMapElement get(int index) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public int indexOf(Object o) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public boolean isEmpty() {
return ExtensionMap.this.isEmpty();
}
#Override
public Iterator<ExtensionMapElement> iterator() {
return new Iterator<ExtensionMapElement>() {
private Iterator<Map.Entry<String, String>> _iter = ExtensionMap.this.entrySet().iterator();
#Override
public boolean hasNext() {
return _iter.hasNext();
}
#Override
public ExtensionMapElement next() {
return new ExtensionMapElement(_iter.next());
}
#Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet.");
}
};
}
#Override
public int lastIndexOf(Object o) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public ListIterator<ExtensionMapElement> listIterator() {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public ListIterator<ExtensionMapElement> listIterator(int index) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public boolean remove(Object o) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public ExtensionMapElement remove(int index) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public ExtensionMapElement set(int index, ExtensionMapElement element) {
add(element);
return null;
}
#Override
public int size() {
return ExtensionMap.this.size();
}
#Override
public List<ExtensionMapElement> subList(int fromIndex, int toIndex) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public Object[] toArray() {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public <T> T[] toArray(T[] a) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
/**
* A utility type that wraps map entries to support a mapping between a
* {#link java.util.Map} interface and a class that can be bound to XML using
* JAXB.
*/
#XmlRootElement(namespace = XMLNamespace.URL)
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(namespace = XMLNamespace.URL)
final class ExtensionMapElement implements Serializable {
/**
* Serialized version unique identifier.
*/
private static final long serialVersionUID = 8211130122512683829L;
/**
* The key of the wrapped map entry.
*/
#XmlAttribute(name = "key", namespace = XMLNamespace.URL, required = true)
private String _key;
/**
* The value of the wrapped map entry.
*/
#XmlElement(name = "value", namespace = XMLNamespace.URL, required = true)
private String _value;
/**
* Default constructor to support JAXB Binding.
*/
public ExtensionMapElement() {
}
/**
* Wraps a map entry with an instance of this class.
*
* #param e
* The map entry to wrap.
*/
public ExtensionMapElement(Map.Entry<String, String> e) {
_key = e.getKey();
_value = e.getValue();
}
/**
* The key of the wrapped map entry.
*
* #return The key of the wrapped map entry.
*/
public String getKey() {
return _key;
}
/**
* The value of the wrapped map entry.
*
* #return The value of the wrapped map entry.
*/
public String getValue() {
return _value;
}
}
Use
public final class ExtensionMap {
private Map<String, String> holder = new HashMap<String, String>();
public String put(String key, String value)
{
return holder.put(key, value);
}
// ...
instead of extanding HashMap.
Java 6 uses
public List<ExtensionMapElement> getEntries()
to get entries, but Java 7 ignore this method becouse you class extends HashMap

Resources