<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[System.Camp - Medium]]></title>
        <description><![CDATA[Coding examples by professional software engineers to help you save time, reduce bugs and make better systems. - Medium]]></description>
        <link>https://medium.com/system-camp?source=rss----2401930e0e89---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>System.Camp - Medium</title>
            <link>https://medium.com/system-camp?source=rss----2401930e0e89---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:48:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/system-camp" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Uploading docs in ElasticSearch using Java with async for super-fast processing with examples]]></title>
            <link>https://medium.com/system-camp/uploading-docs-in-elasticsearch-using-java-with-async-for-super-fast-processing-with-examples-1fd250067c84?source=rss----2401930e0e89---4</link>
            <guid isPermaLink="false">https://medium.com/p/1fd250067c84</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Shashank Agarwal]]></dc:creator>
            <pubDate>Sat, 18 Jul 2020 07:07:12 GMT</pubDate>
            <atom:updated>2020-07-18T07:01:26.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*0XEkIWoLxyfx9dM2.png" /></figure><p>I wanted a quick and easy method to dump a lot of objects to my ElasticSearch endpoint and I did the rookie mistake of adding the “official” maven repository for ElasticSearch for JAVA.</p><p>That jar is so “huge”. It has pretty much all of server and client code. I tweeted about this but looks like there isn’t going to a fix soon.</p><p>Worry not, I was able to find a light-weight ElasticSearch client for JAVA called “Jest”. This is how you install the dependency</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.searchbox&lt;/groupId&gt;<br>    &lt;artifactId&gt;jest&lt;/artifactId&gt;<br>    &lt;version&gt;6.3.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h3>Initializing the client:</h3><p>I signed up for an account on “elastic.co”. The parent company that owns ElasticSearch. Using AWS ElasticSearch was really hard and had a lot of requirements &amp; steps. elastic.co was one click and they also had a free trial, so I went with it.</p><pre>JestClient getJestClient() {<br>    JestClientFactory factory = new JestClientFactory();<br>    factory.setHttpClientConfig(<br>        new HttpClientConfig.Builder(<br>            &quot;https://&lt;your-endpoint&gt;-central1.gcp.cloud.es.io:9243&quot;)<br>            .defaultCredentials(&quot;elastic&quot;, &quot;password&quot;)<br>            .build()<br>    );<br>    return factory.getObject();<br>  }</pre><p>The JestClient offers a lot of APIs but since I want to just dump a lot of documents to my endpoint, I used their bulk async methods. This is how I use it.</p><h3>First, create a list of items of “Index” items.</h3><pre>List&lt;Index&gt; indexList = new ArrayList&lt;&gt;();<br><br>String jsonString = objectMapper.writeValueAsString(feedDao);<br>Index index = new Index.Builder(jsonString).index(&quot;feeds&quot;).type(&quot;doc&quot;)<br>              .id(feedDao.getFeedId()).build();<br>indexList.add(index);</pre><p>My obejct is called “FeedDao” and I convert that to json using objectmapper and just saving it to an indexlist.</p><p>Then you need to create a Bulk request object like this. Make sure you have created your “index” already on ES. You can create index this simple API: <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html">https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html</a></p><p>This is the Bulk Object using builder pattern:</p><pre>Bulk bulk = new Bulk.Builder()<br>     .defaultIndex(&quot;feeds&quot;)<br>     .defaultType(&quot;doc&quot;)<br>     .addAction(indexList)<br>     .build();</pre><p>The way to call an executeAsync is a bit different. You need to be able to handle the failure and successes. You can do whatever you want with the results.</p><pre>jestClient.executeAsync(bulk, new JestResultHandler&lt;JestResult&gt;() {<br>      @Override<br>      public void completed(JestResult result) {<br>        log.info(result);<br>      }<br><br>      @Override<br>      public void failed(Exception ex) {<br>        log.error(ex);<br>      }<br>    });</pre><p>That’s it. I hope this was useful to you. Feel free to bookmark this for later use of you can use the Search of this portal to find this later.</p><p>If there is an error somewhere, please let me know in the comments.</p><p><em>Originally published at </em><a href="https://system.camp/elasticsearch-dump-using-java-with-multi-threading-for-faster-processing/"><em>https://system.camp</em></a><em> on July 18, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fd250067c84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/system-camp/uploading-docs-in-elasticsearch-using-java-with-async-for-super-fast-processing-with-examples-1fd250067c84">Uploading docs in ElasticSearch using Java with async for super-fast processing with examples</a> was originally published in <a href="https://medium.com/system-camp">System.Camp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calling WordPress REST APIs to create users, articles, posts, etc. with examples using JAVA]]></title>
            <link>https://medium.com/system-camp/calling-wordpress-rest-apis-to-create-users-articles-posts-etc-with-examples-using-java-c44f508df07d?source=rss----2401930e0e89---4</link>
            <guid isPermaLink="false">https://medium.com/p/c44f508df07d</guid>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[system]]></category>
            <dc:creator><![CDATA[Shashank Agarwal]]></dc:creator>
            <pubDate>Sat, 18 Jul 2020 07:06:32 GMT</pubDate>
            <atom:updated>2020-07-18T07:06:32.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*l-75fcbVxJvywTkI.png" /></figure><p>Wordpress has an amazing REST API that lets you do pretty much anything that you would need. You can add users, add articles, create tags, create categories etc.</p><p>My backend system is in JAVA and here is how you can do various things in WordPress using JAVA:</p><p>For this we are going to use this really good package: <a href="https://github.com/Afrozaar/wp-api-v2-client-java">https://github.com/Afrozaar/wp-api-v2-client-java</a></p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.afrozaar.wordpress&lt;/groupId&gt;<br>  &lt;artifactId&gt;wp-api-v2-client-java&lt;/artifactId&gt;<br>  &lt;version&gt;4.8.3&lt;/version&gt;<br>  &lt;exclusions&gt;<br>    &lt;exclusion&gt;<br>      &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;<br>      &lt;artifactId&gt;logback-classic&lt;/artifactId&gt;<br>    &lt;/exclusion&gt;<br>    &lt;exclusion&gt;<br>      &lt;groupId&gt;commons-beanutils&lt;/groupId&gt;<br>      &lt;artifactId&gt;commons-beanutils-core&lt;/artifactId&gt;<br>    &lt;/exclusion&gt;<br>    &lt;exclusion&gt;<br>      &lt;groupId&gt;com.fasterxml.jackson.jaxrs&lt;/groupId&gt;<br>      &lt;artifactId&gt;jackson-jaxrs-json-provider&lt;/artifactId&gt;<br>    &lt;/exclusion&gt;<br>  &lt;/exclusions&gt;<br>&lt;/dependency&gt;</pre><p>P.S. I have removed some logging dependencies as they made the jar too big and it was also adding a lot of debug logs that we really don’t need.</p><h3>Creating the Wordpress Client</h3><pre>Wordpress getWordpressClient() {<br>    String baseUrl = &quot;wp-url/wp-json/&quot;;<br>    String username = &quot;admin-email&quot;;<br>    String password = &quot;admin-password&quot;;<br><br>    return ClientFactory<br>      .fromConfig(ClientConfig.of(baseUrl, username, password,<br>          false,<br>          true));<br>}</pre><h3>Creating a Tag</h3><pre>Term term = new Term();<br>term.setName(&quot;tag1);<br>term = wordpress.createTag(term);</pre><h3>Creating a Category</h3><pre>Term term = new Term();<br>term.setName(category);<br>term.setSlug(category);<br>Term cat = wordpress.createCategory(term);</pre><p>The response object will fail if the slug already exists, so its a good idea to wrap this in a try-catch statement.</p><h3>Creating a Post/Article</h3><pre>Post post = PostBuilder.aPost().build();<br>post.setTitle(TitleBuilder.aTitle().withRendered(&quot;title).build());<br>post.setExcerpt(ExcerptBuilder.anExcerpt().withRendered(&quot;description&quot;).build());<br>post.setContent(ContentBuilder.aContent().withRendered(&quot;summary&quot;).build());<br>post.setDate(Instant.now().toString());<br>post.setSlug(&quot;test-article&quot;);<br>post.setAuthor(authorId);<br><br>//Add IDs of tags that you want to add<br>post.setTagIds(tags);<br><br>//Add IDs of categories that you want to add<br>post.setCategoryIds(categoryIds);<br><br>createdPost = wordpress.createPost(post, PostStatus.publish);</pre><h3>Creating a User</h3><pre>User user = new User();<br>user.setEmail(&quot;test@testuser.com&quot;);<br>user.setName(&quot;Name&quot;);<br>user.setSlug(&quot;test&quot;);<br>user.setNickname(name);<br>AvatarUrls avatarUrls = new AvatarUrls();<br>avatarUrls.set96(&quot;user-image-url&quot;);<br>avatarUrls.set48(&quot;user-image-url&quot;);<br>avatarUrls.set24(&quot;user-image-url&quot;);<br>user.setAvatarUrls(avatarUrls);<br>try {<br>  user = wordpress.createUser(user, name, Utils.getAlphaNumericString(20));<br>} catch (UsernameAlreadyExistsException e) {<br>  log.error(e);<br>} catch (UserEmailAlreadyExistsException e) {<br>  log.error(e);<br>}</pre><pre>Media media = new Media();<br>media.setCaption(&quot;caption&quot;);<br>media.setDescription(&quot;description&quot;);<br>media.setAltText(&quot;alt-text&quot;);<br>Resource resource;<br><br>//Load images from a URL, save them local(/tmp) and then upload to<br>// wordpress<br><br>BufferedImage image;<br>try {<br>  String imagePath = Utils.read(&quot;urlToImage&quot;);<br>  File targetFile = new File(imagePath);<br>  <br>  //Only upload image if size is less than 4MB<br>  if ((double) targetFile.length() / (1024 * 1024) &lt; 4.0))) {<br>    resource = new FileSystemResource(targetFile);<br>    media1 = wordpress.createMedia(media, resource);<br>  }<br>} catch (Exception e) {<br>  log.error(e);<br>}</pre><h3>Uploading a Media/Image</h3><pre>Media media = new Media();<br>media.setCaption(&quot;caption&quot;);<br>media.setDescription(&quot;description&quot;);<br>media.setAltText(&quot;alt-text&quot;);<br>Resource resource;</pre><pre>//Load images from a URL, save them local(/tmp) and then upload to<br>// wordpress</pre><pre>BufferedImage image;<br>try {<br>  String imagePath = Utils.read(&quot;urlToImage&quot;);<br>  File targetFile = new File(imagePath);<br>  <br>  //Only upload image if size is less than 4MB<br>  if ((double) targetFile.length() / (1024 * 1024) &lt; 4.0))) {<br>    resource = new FileSystemResource(targetFile);<br>    media1 = wordpress.createMedia(media, resource);<br>  }<br>} catch (Exception e) {<br>  log.error(e);<br>}</pre><p>After creating a “featured image”, WordPress will not make the image available for few seconds to a few minutes. Hence you can’t just add that features image to a post. We overcame this by directly adding an entry into the mysql database.</p><p>This is the code to add a featured Image</p><pre>public void setFeaturedImage(Post post, Media media) {<br>    String sqlQuery = &quot;INSERT INTO `wp_postmeta` (`meta_id`, `post_id`, `meta_key`, `meta_value`) &quot;<br>        + &quot;VALUES (NULL, &quot;<br>        + &quot;&#39;&quot; + post.getId() + &quot;&#39;, &quot;<br>        + &quot;&#39;_thumbnail_id&#39;, &quot;<br>        + &quot;&#39;&quot; + media.getId() + &quot;&#39;)&quot;;<br>    log.info(sqlQuery);<br>    runSqlQuery(sqlQuery);<br>  }</pre><p>Hope you guys find this helpful. Let me know if you find any errors in the code.</p><p><em>Originally published at </em><a href="https://system.camp/adding-users-articles-to-wordpress-using-java/"><em>https://system.camp</em></a><em> on July 16, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c44f508df07d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/system-camp/calling-wordpress-rest-apis-to-create-users-articles-posts-etc-with-examples-using-java-c44f508df07d">Calling WordPress REST APIs to create users, articles, posts, etc. with examples using JAVA</a> was originally published in <a href="https://medium.com/system-camp">System.Camp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-threading in JAVA using “Executors”]]></title>
            <link>https://medium.com/system-camp/multi-threading-in-java-using-executors-de697e84e007?source=rss----2401930e0e89---4</link>
            <guid isPermaLink="false">https://medium.com/p/de697e84e007</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[threading-in-java]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Shashank Agarwal]]></dc:creator>
            <pubDate>Sat, 18 Jul 2020 07:03:07 GMT</pubDate>
            <atom:updated>2020-07-18T07:03:07.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*fpfWAr_i_7So0hIX.png" /></figure><p>Multi-threading is not always super easy to implement. There is Runnable, Thread, and all sorts of frameworks/packages but we love the executors class to run our code in threads.</p><p>Here is the code:</p><p>A time-consuming function such as an API call, download files, etc.</p><pre>public Double someTimeConsumingFunction() throws InterruptedException {<br>  log.info(&quot;Thread started&quot;);<br>  Thread.sleep(1000);<br>  log.info(&quot;Thread finished&quot;);<br>  return Math.random();<br>}</pre><p>Our multi-threaded function</p><pre>public void threadsExample() {<br>  ExecutorService taskExecutor = Executors.newFixedThreadPool(25);<br>  List&lt;Future&lt;Double&gt;&gt; resultList = new ArrayList&lt;&gt;();<br><br>  for (int i = 0; i &lt; 10; i++) {<br>    Future&lt;Double&gt; result = taskExecutor<br>        .submit(new Callable&lt;Double&gt;() {<br>          public Double call() {<br>            try {<br>              return someTimeConsumingFunction();<br>            } catch (Exception e) {<br>              log.error(e);<br>            }<br>            return null;<br>          }<br>        });<br>    resultList.add(result);<br>  }<br>  taskExecutor.shutdown();<br>  try {<br>    log.info(&quot;Waiting for all threads to finish and terminate&quot;);<br>    taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);<br>  } catch (InterruptedException e) {<br>    Sentry.capture(e);<br>  }<br>  log.info(&quot;Finished execution&quot;);<br>}</pre><p>As simple as that. I have actually bookmarked this page as I keep using this code again and again. Let me know in the comments if anything is unclear.</p><p><em>Originally published at </em><a href="https://system.camp/multi-threading-in-java-using-executors/"><em>https://system.camp</em></a><em> on July 17, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de697e84e007" width="1" height="1" alt=""><hr><p><a href="https://medium.com/system-camp/multi-threading-in-java-using-executors-de697e84e007">Multi-threading in JAVA using “Executors”</a> was originally published in <a href="https://medium.com/system-camp">System.Camp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>