How to pass text as input in a POST request body with Jax-RS

Use MediaType.TEXT_PLAIN in the @Consumes annotation and then you have access to the text content as string

    @POST
    @Path("organisation")
    @Consumes(MediaType.TEXT_PLAIN)
    @ApiOperation(value = "Create bookmark from text")
    @ApiResponses(
            @ApiResponse(code = 201, message = "Bookmark successfully created.", response = Bookmark.class),
            @ApiResponse(code = 403, message = "Forbidden")
    )
    public Response createBookmark(@ApiParam("Bookmark") String boookmark, @Context UriInfo uriInfo) throws JAXBException 
        Bookmark created = bookmarkService.createBookmarkFromString(bookmark);
        UriBuilder builder = uriInfo.getAbsolutePathBuilder();
        builder.path(created.getUuid().toString());
        return Response.created(builder.build()).build();
    

Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.


Source link

How to read file from test resources in java unit test

Use the getClass().getClassLoader().getResourceAsStream() to get an InputStream for the wanted resource. In the following snippet we access the bookmark-example.xml file resource, which is placed directly in the src/test/resources folder:

@Test
void shouldUnmarshallXmlToJava() throws JAXBException 
    JAXBContext jaxbContext = JAXBContext.newInstance("dev.codepal.bookmark");
    final var jaxbUnmarshaller = jaxbContext.createUnmarshaller();

    InputStream inStream = getClass().getClassLoader().getResourceAsStream(
            "bookmark-example.xml");

    JAXBElement<Bookmark> o = (JAXBElement<Bookmark>)jaxbUnmarshaller.unmarshal(inStream);
    Bookmark bookmark = o.getValue();
    assertThat(bookmark.getTitle(), equalTo("CodepediaOrg"));

Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.


Source link

How to sanitize your urls in angular

Project: codeverFile: backup-bookmarks-dialog.component.ts

On Codever you can backup your bookmarks and snippets. When backing up you are presented a dialog where you can choose to display the items in browser. For that we use a blob URL we know for sure it is safe.

To not get the unsafe prefix in your generated html I use the DomSanitizer and its method bypassSecurityTrustUrl as shown in the example below:

export class BackupBookmarksDialogComponent implements OnInit {

  backupType: string; // 'bookmarks' | 'snippets';
  blobUrl: any;
  sanitizedBlobUrl: any;
  filename: string;

  constructor(
    private dialogRef: MatDialogRef<BackupBookmarksDialogComponent>,
    private router: Router,
    @Inject(MAT_DIALOG_DATA) data,
    private sanitizer: DomSanitizer
  ) 
    this.sanitizedBlobUrl = 
    this.sanitizer.bypassSecurityTrustUrl(data.blobUrl);
    this.blobUrl = data.blobUrl;
    this.backupType = data.backupType;
    const currentDate = new Date();
    this.filename = `$this.backupType_$currentDate.toISOString().json`;
  

In the html component the sanitizedBlogUrl is injected in the href attribute of the a html element

  <a [href]="sanitizedBlobUrl" [download]="filename" type="button" class="btn btn-primary btn-sm mr-2" (click)="download()"><i class="fas fa-download"></i> Download
  </a>


Reference –

https://angular.io/api/platform-browser/DomSanitizer

Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.


Source link

SQL Select with IN clause from list with JPA

The native SQL query we want to map in JPA is similar to the following:

SELECT * FROM PARTNER where PARTNER_NUMBER IN ('id1', 'idn').

With JPA you can use a TypedQuery for example and set the expected list of the IN clause directly as query parameter

@Stateless
public class PartnerDataRepository 

    @Inject private EntityManager em;

    public List<PartnerData> findPartnerDataFromList(
        List<String> partnerNumbers) 
      TypedQuery<PartnerData> query =
          em.createNamedQuery(
              PartnerData.FIND_PARTNER_DATA_IN_LIST, PartnerData.class);
      query.setParameter(PartnerData.PARTNER_NUMBERS, partnerNumbers);

      return query.getResultList();
    

In the named query itself you can pass the parameter with : as you would when setting a “normal” parameter:

@Entity
@Access(AccessType.FIELD)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = PartnerData.TABLE_NAME)
@NamedQueries(
  @NamedQuery(
      name = PartnerData.FIND_PARTNER_DATA_IN_LIST,
      query = "select m from PartnerData m where partnerNumber in :partnerNumbers")
)
public class PartnerData 
  public static final String TABLE_NAME = "PARTNER";

  public static final String PARTNER_NUMBERS = "partnerNumbers";
  public static final String FIND_PARTNER_DATA_IN_LIST =
      "findPartnerDataWithPartnerNumbers";

  //... rest ignored for brevity



Shared ❤️ from Codever. 👉 use the copy to mine functionality to add it to your personal snippets collection.


Source link

Force null value check on field mapping in Mapstruct

Use the nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS on the mapping property you want to be checked. In the following snippet you can see a PostalAdress entity is mapped to an entity of the same type, but the id is overwritten only when it is present in the source:

import java.time.LocalDateTime;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.NullValueCheckStrategy;

import com.example.entity.PostalAddress;

@Mapper(
    componentModel = "cdi",
    imports = LocalDateTime.class)
public interface PostalAddressEntity2EntityMapperService 

  @Mapping(source = "id", target = "id", nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
  PostalAddress toPostalAddressntityToPostalAddressEntity(
      PostalAddress PostalAddress);

This will generate something similar with the following

package com.example.entitytoentity;

import com.example.entity.PostalAddress;
import java.time.LocalDateTime;
import javax.annotation.processing.Generated;
import javax.enterprise.context.ApplicationScoped;

@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2021-09-01T14:28:11+0200",
    comments = "version: 1.4.2.Final, compiler: javac, environment: Java 11.0.12 (Azul Systems, Inc.)"
)
@ApplicationScoped
public class PostalAddressEntity2EntityMapperServiceImpl implements PostalAddressEntity2EntityMapperService 

    @Override
    public PostalAddress toPostalAddressEntity(PostalAddress PostalAddress) 
        if ( PostalAddress == null ) 
            return null;
        

        PostalAddress PostalAddress1 = new PostalAddress();

        if ( PostalAddress.getId() != null ) 
            PostalAddress1.setId( PostalAddress.getId() );
        
        PostalAddress1.setStreeNo( PostalAddress.getStreetNo() );
        PostalAddress1.setStreet( PostalAddress.getStreet() );
        PostalAddress1.setMainAdress( PostalAddress.getMainAdress() );

        return PostalAddress1;
    



Shared ❤️ from Codever.   👉 use the copy to mine functionality to add it to your personal snippets collection.


Source link

Get user input value from input box in visual studio code

Use vscode.window.showInputBox – the returned value will be undefined if the input box was canceled (e.g. pressing ESC). Otherwise the returned value will be the string typed by the user or an empty string if the user did not type anything but dismissed the input box with OK.

const searchQuery = await vscode.window.showInputBox(
  placeHolder: "Search query",
  prompt: "Search my snippets on Codever",
  value: selectedText
);
if(searchQuery === '')
  console.log(searchQuery);
  vscode.window.showErrorMessage('A search query is mandatory to execute this action');


if(searchQuery !== undefined)
  const searchUrl = `https://www.codever.land/search?q=$searchQuery&sd=my-snippets`;
  vscode.env.openExternal(Uri.parse(searchUrl));

You can see it in action below:

vs-code-extension-search


The whole source for the Codever Snippets VSCode extension on Github.


Shared ❤️ from Codever.   👉   use the copy to mine functionality to add it to your personal snippets collection.


Source link