The code first login to Magento site using the admin account (to login as a client, call uploader.loginAsClient(...) instead).
Next, it then obtain the first 10 products from the Magento site, for each product its product id is used to retrieve the image file stored locally in the /tmp/images folder. The /tmp/images folder has the following images
/tmp/images/1.jpg
/tmp/images/2.jpg
/tmp/images/3.jpg
/tmp/images/4.jpg
/tmp/images/5.jpg
/tmp/images/6.jpg
The mapping between each product and each page is done by (product) -> (product.productId % 6 + 1).jpg. Note that it is feasible to upload multiple images for each product (as evidenced by the line 'Arrays.asList...' in the above code).
The 'overwrite' flag if set to true will delete all images originally associated with the product before upload the new images for the product. If set to false, it will not upload any images if there already been images associated with the product.
To upload png images, use uploadPng(...) instead of uploadJpeg(...)
Support for token based authentication (ideal for Android or Spring application)
Support for V1 rest api at the current version of Magento which is Magento2 version 2.16
Allow access to:
Product (CRUD)
Product Media (CRUD)
Product Inventory (RU)
Product Categories (CRUD)
Account (R)
The java client provides access to web apis as listed in link and link2 currently available for Magent 2.16.
As Magento2 by default enable a feature preventing anonymous access to most of the web APIs which could cause third-party integrations to fail. If a third-party integration calls any of these web APIs, it will receive an authentication error instead of the expected response. In this case, you might need to disable this feature. To disable this feature, log in to the Admin panel and navigate to Stores > Configuration > Services > Magento Web API > Web API Security. Then select Yes from the Allow Anonymous Guest Access menu.
Usage
Customer Login
The sample code below shows how to login to magento site and retrieve the current login account information:
The sample code below shows how to list products, get/add/update/delete a particular product by its sku
MagentoClient client =newMagentoClient(magento_site_url);
client.loginAsAdmin(username, password);
int pageIndex =0;
int pageSize =10;
ProductPage page = client.products().page(pageIndex, pageSize);
List<Product> products = page.getItems();
// check if product by sku existsboolean exists = client.products().hasProduct(sku);
// get product detail Product product = client.products().getProductBySku(sku);
// create or update a product Product newProduct =newProduct();
newProduct.setSku("B203-SKU");
newProduct.setName("B203");
newProduct.setPrice(30.00);
newProduct.setStatus(1);
newProduct.setType_id("simple");
newProduct.setAttribute_set_id(4);
newProduct.setWeight(1);
Product saveProduct = client.products().addProduct(newProduct);
// delete a product
client.products().deleteProduct(sku);
Product Media
The sample code below shows how to list the media associated with a particular product:
String productSku ="B202-SKU";
List<ProductMedia> mediaList = client.media().getProductMediaList(productSku);
// below returns a list of absoluate/relative urls for the media (e.g. images) associated with the productList<String> imageUrls = client.media().getProductMediaAbsoluteUrls(productSku);
List<String> imageUrls = client.media().getProductMediaRelativeUrls(productSku);
In the above code,the entry id of a product media associated with the product can be obtained by calling the ProductMedia.getId() api.
The sample code below shows how to obtain a particular media associated with a product:
String productSku ="B202-SKU";
long entryId =1L;
ProductMedia media = client.media().getProductMedia(productSku, entryId);
// below returns a list of absoluate/relative urls for the media (e.g. images) associated with the productString imageUrl = client.media().getProductMediaAbsoluteUrl(productSku, entryId);
String imageUrl = client.media().getProductMediaRelativeUrl(productSku, entryId);
The sample code below shows how to upload an image for a particular product given the bytes of the image file:
The uploadedEntryId returned is the entry id created for the newly uploaded image.
The sample code below shows how to update an image media for a particular product given the bytes of the new image:
String productSku ="B202-SKU";
String imageFileName ="new_image.png";
InputStream inputStream =newFileInputStream(imageFileName);
ByteArrayOutputStream baos =newByteArrayOutputStream();
int length;
byte[] bytes =newbyte[1024];
while((length = inputStream.read(bytes, 0, 1024)) >0) {
baos.write(bytes, 0, length);
}
bytes = baos.toByteArray();
long entryId =1L; // entry id of the media to be updatedboolean updated = client.media().updateImage(productSku, entryId, bytes, ImageType.Png);
The sample code below shows how to update an image media for a particular product given the file path of the new image:
String productSku ="B202-SKU";
String imageFilePath ="new_image.png";
long entryId =1L; // entry id of the media to be updatedboolean updated = client.media().updateImage(productSku, entryId, imageFilePath);
The sample code below shows how to delete an image or a video associated with a particular product:
String productSku ="B202-SKU";
long entryId =1L; // entry id of the media to be deletedboolean deleted = client.media().deleteProductMedia(productSku, entryId);
Product Categories
The sample code below show how to list/add/update/delete categories, get a particular category,
MagentoClient client =newMagentoClient(magento_site_url);
client.loginAsAdmin(username, password);
// list categoriesCategory page = client.categories().all();
// get the category that has category_id = 15 (Clean means no children of that category will be returned)Category category15 = client.categories().getCategoryByIdClean(15);
Category category15 = client.categories().getCategoryByIdWithChildren(15);
// delete category with category id = 15
client.categories().deleteCategory(15);
Category newCategory =...
client.categories().addCategory(newCategory);
newCategory.setName("New Category Name");
client.categories().updateCategory(newCategory);
The sample code below show how to list/add/remove products under a category:
// list products under category 15List<CategoryProduct> products = client.categories().getProductsInCategory(15);
// add product to categorylong categoryId =15;
String productSku ="B202-SKU";
int position =1;
boolean added = client.categories().addProductToCategory(categoryId, productSku, position);
// remove product from categoryboolean removed = client.categories().removeProductFromCategory(categoryId, productSku);
Product Inventory
The sample code below shows how to obtain and update the inventory information for a particular product sku:
MagentoClient client =newMagentoClient(magento_site_url);
client.loginAsAdmin(username, password);
String productSku ="product_dynamic_571";
StockItems inventory_for_sku = client.inventory().getStockItems(productSku);
// to update the inventory for the product
inventory_for_sku.setQty(10);
String stockId = client.inventory().saveStockItems(productSku, inventory_for_sku);
I have just upload Vagrantfile for latest magento (2.16) and latest Ubuntu (bento/ubuntu-14.04) to github so that interested readers can install the latest magento for development via Vagrant on their computer:
The github repo contains the Vagrantfile and Vagrantfile.config.yml adopted from the "Magento Developer Guide" book but updated based on the trial-and-errors with the latest magento, ubuntu and PHP
The objective is to address several issues with the original Vagrantfile provided by "Magento Developer Guide" so that it is compatible with the latest magento (current version 2.16) and Ubuntu (current version: Ubuntu 14.04.5 LTS)
Some known issues with the original Vagrantfile provided by "Magento Developer Guide" are:
The vm.box "ubuntu/vivid64" for vagrant is not longer provided
The default PHP version (7.1) provided by latest ubuntu (after running apt-get update on bento/ubuntu-14.04) is not compatible with magento 2.16 due to the issues with mcrypt no longer supported in PHP 7.1
php5.6-mbstring and php5.6-zip are needed for the magento 2.16 to work correctly
Version
The following list the version of the various softwares installed by the Vagrantfile on the ubuntu VM:
vm.box: bento/ubuntu-14.04
magento: magento 2 (version: 2.16)
PHP: 5.6
MySQL: 5.6
Currently the Vagrantfile is tested to be working on host computer which is Windows 10
Obtain the magento public and private secret keys (Follow this link) and replace the "[magent_public_key]" and "[magento_private_key]" in Vagrantfile.config.yml with the obtained keys
Obtain a github oauth access key (Follow this link and replace the "[github_oauth]" in Vagrantfile.config.yml with the obtained github oauth token
Change the "email@change.me" in Vagrantfile.config.yml to your email of choice
Change the "[magento_host_path]" in Vagrantfile.config.yml to your local path on your host computer on which you want the magento files to be installed
Run the following command on your host computer:
git clone https://github.com/chen0040/vagrant-magento-2.16.git
cd vagrant-magento-2.16
vagrant up
Add the line "192.168.10.10 magento.box" to /etc/hosts on your host computer (If you host computer is Windows, then the hosts file is located at C:\Windows\System32\drivers\etc\hosts)
Open your browser and enter "http://magento.box" (To change this to your url of choice, replace it in the Vagrantfile.config.yml)
To login to the vagrant vm box, run the command "vagrant ssh". If you are using putty, ssh to 192.168.10.10 (username: vagrant, password: vagrant)
Issues and Solutions
If you encounter some of the issues when running Vagrantfile, you can refer to the following:
Issue: Vagrant was unable to mount VirtualBox shared folders. This is usually because the filesystem "vboxsf" is not available. This filesystem is made available via the VirtualBox Guest Additions and kernel module.