code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
package pl.polidea.treeview.demo;
import java.util.Arrays;
import java.util.Set;
import pl.polidea.treeview.AbstractTreeViewAdapter;
import pl.polidea.treeview.R;
import pl.polidea.treeview.TreeNodeInfo;
import pl.polidea.treeview.TreeStateManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* This is a very simple adapter that provides very basic tree view with a
* checkboxes and simple item description.
*
*/
class SimpleStandardAdapter extends AbstractTreeViewAdapter<Long> {
private final Set<Long> selected;
private final OnCheckedChangeListener onCheckedChange = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final CompoundButton buttonView,
final boolean isChecked) {
final Long id = (Long) buttonView.getTag();
changeSelected(isChecked, id);
}
};
private void changeSelected(final boolean isChecked, final Long id) {
if (isChecked) {
selected.add(id);
} else {
selected.remove(id);
}
}
public SimpleStandardAdapter(final TreeViewListDemo treeViewListDemo,
final Set<Long> selected,
final TreeStateManager<Long> treeStateManager,
final int numberOfLevels) {
super(treeViewListDemo, treeStateManager, numberOfLevels);
this.selected = selected;
}
private String getDescription(final long id) {
final Integer[] hierarchy = getManager().getHierarchyDescription(id);
return "Node " + id + Arrays.asList(hierarchy);
}
@Override
public View getNewChildView(final TreeNodeInfo<Long> treeNodeInfo) {
final LinearLayout viewLayout = (LinearLayout) getActivity()
.getLayoutInflater().inflate(R.layout.demo_list_item, null);
return updateView(viewLayout, treeNodeInfo);
}
@Override
public LinearLayout updateView(final View view,
final TreeNodeInfo<Long> treeNodeInfo) {
final LinearLayout viewLayout = (LinearLayout) view;
final TextView descriptionView = (TextView) viewLayout
.findViewById(R.id.demo_list_item_description);
final TextView levelView = (TextView) viewLayout
.findViewById(R.id.demo_list_item_level);
descriptionView.setText(getDescription(treeNodeInfo.getId()));
levelView.setText(Integer.toString(treeNodeInfo.getLevel()));
final CheckBox box = (CheckBox) viewLayout
.findViewById(R.id.demo_list_checkbox);
box.setTag(treeNodeInfo.getId());
if (treeNodeInfo.isWithChildren()) {
box.setVisibility(View.GONE);
} else {
box.setVisibility(View.VISIBLE);
box.setChecked(selected.contains(treeNodeInfo.getId()));
}
box.setOnCheckedChangeListener(onCheckedChange);
return viewLayout;
}
@Override
public void handleItemClick(final View view, final Object id) {
final Long longId = (Long) id;
final TreeNodeInfo<Long> info = getManager().getNodeInfo(longId);
if (info.isWithChildren()) {
super.handleItemClick(view, id);
} else {
final ViewGroup vg = (ViewGroup) view;
final CheckBox cb = (CheckBox) vg
.findViewById(R.id.demo_list_checkbox);
cb.performClick();
}
}
@Override
public long getItemId(final int position) {
return getTreeId(position);
}
} | 0812398-clonetreeview | src/pl/polidea/treeview/demo/SimpleStandardAdapter.java | Java | bsd | 3,723 |
package pl.polidea.treeview.demo;
import java.util.Set;
import pl.polidea.treeview.R;
import pl.polidea.treeview.TreeNodeInfo;
import pl.polidea.treeview.TreeStateManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
final class FancyColouredVariousSizesAdapter extends SimpleStandardAdapter {
public FancyColouredVariousSizesAdapter(final TreeViewListDemo activity,
final Set<Long> selected,
final TreeStateManager<Long> treeStateManager,
final int numberOfLevels) {
super(activity, selected, treeStateManager, numberOfLevels);
}
@Override
public LinearLayout updateView(final View view,
final TreeNodeInfo<Long> treeNodeInfo) {
final LinearLayout viewLayout = super.updateView(view, treeNodeInfo);
final TextView descriptionView = (TextView) viewLayout
.findViewById(R.id.demo_list_item_description);
final TextView levelView = (TextView) viewLayout
.findViewById(R.id.demo_list_item_level);
descriptionView.setTextSize(20 - 2 * treeNodeInfo.getLevel());
levelView.setTextSize(20 - 2 * treeNodeInfo.getLevel());
return viewLayout;
}
@Override
public Drawable getBackgroundDrawable(final TreeNodeInfo<Long> treeNodeInfo) {
switch (treeNodeInfo.getLevel()) {
case 0:
return new ColorDrawable(Color.WHITE);
case 1:
return new ColorDrawable(Color.GRAY);
case 2:
return new ColorDrawable(Color.YELLOW);
default:
return null;
}
}
} | 0812398-clonetreeview | src/pl/polidea/treeview/demo/FancyColouredVariousSizesAdapter.java | Java | bsd | 1,767 |
package pl.polidea.treeview.demo;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import pl.polidea.treeview.InMemoryTreeStateManager;
import pl.polidea.treeview.R;
import pl.polidea.treeview.TreeBuilder;
import pl.polidea.treeview.TreeNodeInfo;
import pl.polidea.treeview.TreeStateManager;
import pl.polidea.treeview.TreeViewList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
/**
* Demo activity showing how the tree view can be used.
*
*/
public class TreeViewListDemo extends Activity {
private enum TreeType implements Serializable {
SIMPLE,
FANCY
}
private final Set<Long> selected = new HashSet<Long>();
private static final String TAG = TreeViewListDemo.class.getSimpleName();
private TreeViewList treeView;
private static final int[] DEMO_NODES = new int[] { 0, 0, 1, 1, 1, 2, 2, 1,
1, 2, 1, 0, 0, 0, 1, 2, 3, 2, 0, 0, 1, 2, 0, 1, 2, 0, 1 };
private static final int LEVEL_NUMBER = 4;
private TreeStateManager<Long> manager = null;
private FancyColouredVariousSizesAdapter fancyAdapter;
private SimpleStandardAdapter simpleAdapter;
private TreeType treeType;
private boolean collapsible;
@SuppressWarnings("unchecked")
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TreeType newTreeType = null;
boolean newCollapsible;
if (savedInstanceState == null) {
manager = new InMemoryTreeStateManager<Long>();
final TreeBuilder<Long> treeBuilder = new TreeBuilder<Long>(manager);
for (int i = 0; i < DEMO_NODES.length; i++) {
treeBuilder.sequentiallyAddNextNode((long) i, DEMO_NODES[i]);
}
Log.d(TAG, manager.toString());
newTreeType = TreeType.SIMPLE;
newCollapsible = true;
} else {
manager = (TreeStateManager<Long>) savedInstanceState
.getSerializable("treeManager");
newTreeType = (TreeType) savedInstanceState
.getSerializable("treeType");
newCollapsible = savedInstanceState.getBoolean("collapsible");
}
setContentView(R.layout.main_demo);
treeView = (TreeViewList) findViewById(R.id.mainTreeView);
fancyAdapter = new FancyColouredVariousSizesAdapter(this, selected,
manager, LEVEL_NUMBER);
simpleAdapter = new SimpleStandardAdapter(this, selected, manager,
LEVEL_NUMBER);
setTreeAdapter(newTreeType);
setCollapsible(newCollapsible);
registerForContextMenu(treeView);
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
outState.putSerializable("treeManager", manager);
outState.putSerializable("treeType", treeType);
outState.putBoolean("collapsible", this.collapsible);
super.onSaveInstanceState(outState);
}
protected final void setTreeAdapter(final TreeType newTreeType) {
this.treeType = newTreeType;
switch (newTreeType) {
case SIMPLE:
treeView.setAdapter(simpleAdapter);
break;
case FANCY:
treeView.setAdapter(fancyAdapter);
break;
default:
treeView.setAdapter(simpleAdapter);
}
}
protected final void setCollapsible(final boolean newCollapsible) {
this.collapsible = newCollapsible;
treeView.setCollapsible(this.collapsible);
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
final MenuItem collapsibleMenu = menu
.findItem(R.id.collapsible_menu_item);
if (collapsible) {
collapsibleMenu.setTitle(R.string.collapsible_menu_disable);
collapsibleMenu.setTitleCondensed(getResources().getString(
R.string.collapsible_condensed_disable));
} else {
collapsibleMenu.setTitle(R.string.collapsible_menu_enable);
collapsibleMenu.setTitleCondensed(getResources().getString(
R.string.collapsible_condensed_enable));
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (item.getItemId() == R.id.simple_menu_item) {
setTreeAdapter(TreeType.SIMPLE);
} else if (item.getItemId() == R.id.fancy_menu_item) {
setTreeAdapter(TreeType.FANCY);
} else if (item.getItemId() == R.id.collapsible_menu_item) {
setCollapsible(!this.collapsible);
} else if (item.getItemId() == R.id.expand_all_menu_item) {
manager.expandEverythingBelow(null);
} else if (item.getItemId() == R.id.collapse_all_menu_item) {
manager.collapseChildren(null);
} else {
return false;
}
return true;
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View v,
final ContextMenuInfo menuInfo) {
final AdapterContextMenuInfo adapterInfo = (AdapterContextMenuInfo) menuInfo;
final long id = adapterInfo.id;
final TreeNodeInfo<Long> info = manager.getNodeInfo(id);
final MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.context_menu, menu);
if (info.isWithChildren()) {
if (info.isExpanded()) {
menu.findItem(R.id.context_menu_expand_item).setVisible(false);
menu.findItem(R.id.context_menu_expand_all).setVisible(false);
} else {
menu.findItem(R.id.context_menu_collapse).setVisible(false);
}
} else {
menu.findItem(R.id.context_menu_expand_item).setVisible(false);
menu.findItem(R.id.context_menu_expand_all).setVisible(false);
menu.findItem(R.id.context_menu_collapse).setVisible(false);
}
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(final MenuItem item) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
final long id = info.id;
if (item.getItemId() == R.id.context_menu_collapse) {
manager.collapseChildren(id);
return true;
} else if (item.getItemId() == R.id.context_menu_expand_all) {
manager.expandEverythingBelow(id);
return true;
} else if (item.getItemId() == R.id.context_menu_expand_item) {
manager.expandDirectChildren(id);
return true;
} else if (item.getItemId() == R.id.context_menu_delete) {
manager.removeNodeRecursively(id);
return true;
} else {
return super.onContextItemSelected(item);
}
}
} | 0812398-clonetreeview | src/pl/polidea/treeview/demo/TreeViewListDemo.java | Java | bsd | 7,417 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.multiple;
import java.util.List;
import java.util.regex.Pattern;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class BasicCrawler extends WebCrawler {
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
private String[] myCrawlDomains;
@Override
public void onStart() {
myCrawlDomains = (String[]) myController.getCustomData();
}
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
if (FILTERS.matcher(href).matches()) {
return false;
}
for (String crawlDomain : myCrawlDomains) {
if (href.startsWith(crawlDomain)) {
return true;
}
}
return false;
}
@Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
int parentDocid = page.getWebURL().getParentDocid();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Docid of parent page: " + parentDocid);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
System.out.println("=============");
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/multiple/BasicCrawler.java | Java | asf20 | 2,650 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.multiple;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class MultipleCrawlerController {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Needed parameter: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
CrawlConfig config1 = new CrawlConfig();
CrawlConfig config2 = new CrawlConfig();
/*
* The two crawlers should have different storage folders for their
* intermediate data
*/
config1.setCrawlStorageFolder(crawlStorageFolder + "/crawler1");
config2.setCrawlStorageFolder(crawlStorageFolder + "/crawler2");
config1.setPolitenessDelay(1000);
config2.setPolitenessDelay(2000);
config1.setMaxPagesToFetch(50);
config2.setMaxPagesToFetch(100);
/*
* We will use different PageFetchers for the two crawlers.
*/
PageFetcher pageFetcher1 = new PageFetcher(config1);
PageFetcher pageFetcher2 = new PageFetcher(config2);
/*
* We will use the same RobotstxtServer for both of the crawlers.
*/
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher1);
CrawlController controller1 = new CrawlController(config1, pageFetcher1, robotstxtServer);
CrawlController controller2 = new CrawlController(config2, pageFetcher2, robotstxtServer);
String[] crawler1Domains = new String[] { "http://www.ics.uci.edu/", "http://www.cnn.com/" };
String[] crawler2Domains = new String[] { "http://en.wikipedia.org/" };
controller1.setCustomData(crawler1Domains);
controller2.setCustomData(crawler2Domains);
controller1.addSeed("http://www.ics.uci.edu/");
controller1.addSeed("http://www.cnn.com/");
controller1.addSeed("http://www.ics.uci.edu/~lopes/");
controller1.addSeed("http://www.cnn.com/POLITICS/");
controller2.addSeed("http://en.wikipedia.org/wiki/Main_Page");
controller2.addSeed("http://en.wikipedia.org/wiki/Obama");
controller2.addSeed("http://en.wikipedia.org/wiki/Bing");
/*
* The first crawler will have 5 cuncurrent threads and the second
* crawler will have 7 threads.
*/
controller1.startNonBlocking(BasicCrawler.class, 5);
controller2.startNonBlocking(BasicCrawler.class, 7);
controller1.waitUntilFinish();
System.out.println("Crawler 1 is finished.");
controller2.waitUntilFinish();
System.out.println("Crawler 2 is finished.");
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/multiple/MultipleCrawlerController.java | Java | asf20 | 3,711 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.statushandler;
import java.util.regex.Pattern;
import org.apache.http.HttpStatus;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class StatusHandlerCrawler extends WebCrawler {
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
/**
* You should implement this function to specify whether
* the given url should be crawled or not (based on your
* crawling logic).
*/
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready
* to be processed by your program.
*/
@Override
public void visit(Page page) {
// Do nothing
}
@Override
protected void handlePageStatusCode(WebURL webUrl, int statusCode, String statusDescription) {
if (statusCode != HttpStatus.SC_OK) {
if (statusCode == HttpStatus.SC_NOT_FOUND) {
System.out.println("Broken link: " + webUrl.getURL() + ", this link was found in page: " + webUrl.getParentUrl());
} else {
System.out.println("Non success status for link: " + webUrl.getURL() + ", status code: " + statusCode + ", description: " + statusDescription);
}
}
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/statushandler/StatusHandlerCrawler.java | Java | asf20 | 2,391 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.statushandler;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class StatusHandlerCrawlController {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
/*
* numberOfCrawlers shows the number of concurrent threads that should
* be initiated for crawling.
*/
int numberOfCrawlers = Integer.parseInt(args[1]);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
/*
* Be polite: Make sure that we don't send more than 1 request per
* second (1000 milliseconds between requests).
*/
config.setPolitenessDelay(1000);
/*
* You can set the maximum crawl depth here. The default value is -1 for
* unlimited depth
*/
config.setMaxDepthOfCrawling(2);
/*
* You can set the maximum number of pages to crawl. The default value
* is -1 for unlimited number of pages
*/
config.setMaxPagesToFetch(1000);
/*
* Do you need to set a proxy? If so, you can use:
* config.setProxyHost("proxyserver.example.com");
* config.setProxyPort(8080);
*
* If your proxy also needs authentication:
* config.setProxyUsername(username); config.getProxyPassword(password);
*/
/*
* This config parameter can be used to set your crawl to be resumable
* (meaning that you can resume the crawl from a previously
* interrupted/crashed crawl). Note: if you enable resuming feature and
* want to start a fresh crawl, you need to delete the contents of
* rootFolder manually.
*/
config.setResumableCrawling(false);
/*
* Instantiate the controller for this crawl.
*/
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
/*
* For each crawl, you need to add some seed urls. These are the first
* URLs that are fetched and then the crawler starts following links
* which are found in these pages
*/
controller.addSeed("http://www.ics.uci.edu/~welling/");
controller.addSeed("http://www.ics.uci.edu/~lopes/");
controller.addSeed("http://www.ics.uci.edu/");
/*
* Start the crawl. This is a blocking operation, meaning that your code
* will reach the line after this only when crawling is finished.
*/
controller.start(StatusHandlerCrawler.class, numberOfCrawlers);
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/statushandler/StatusHandlerCrawlController.java | Java | asf20 | 3,971 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.shutdown;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class ControllerWithShutdown {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
/*
* numberOfCrawlers shows the number of concurrent threads that should
* be initiated for crawling.
*/
int numberOfCrawlers = Integer.parseInt(args[1]);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
config.setPolitenessDelay(1000);
// Unlimited number of pages can be crawled.
config.setMaxPagesToFetch(-1);
/*
* Instantiate the controller for this crawl.
*/
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
/*
* For each crawl, you need to add some seed urls. These are the first
* URLs that are fetched and then the crawler starts following links
* which are found in these pages
*/
controller.addSeed("http://www.ics.uci.edu/~welling/");
controller.addSeed("http://www.ics.uci.edu/~lopes/");
controller.addSeed("http://www.ics.uci.edu/");
/*
* Start the crawl. This is a blocking operation, meaning that your code
* will reach the line after this only when crawling is finished.
*/
controller.startNonBlocking(BasicCrawler.class, numberOfCrawlers);
// Wait for 30 seconds
Thread.sleep(30 * 1000);
// Send the shutdown request and then wait for finishing
controller.shutdown();
controller.waitUntilFinish();
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/shutdown/ControllerWithShutdown.java | Java | asf20 | 3,150 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.shutdown;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.List;
import java.util.regex.Pattern;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class BasicCrawler extends WebCrawler {
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
private final static String DOMAIN = "http://www.ics.uci.edu/";
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith(DOMAIN);
}
@Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
int parentDocid = page.getWebURL().getParentDocid();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Docid of parent page: " + parentDocid);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
System.out.println("=============");
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/shutdown/BasicCrawler.java | Java | asf20 | 2,463 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.imagecrawler;
import java.security.MessageDigest;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class Cryptography {
private static final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
'f' };
public static String MD5(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
return hexStringFromBytes(md.digest());
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static String hexStringFromBytes(byte[] b) {
String hex = "";
int msb;
int lsb;
int i;
// MSB maps to idx 0
for (i = 0; i < b.length; i++) {
msb = (b[i] & 0x000000FF) / 16;
lsb = (b[i] & 0x000000FF) % 16;
hex = hex + hexChars[msb] + hexChars[lsb];
}
return (hex);
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/imagecrawler/Cryptography.java | Java | asf20 | 1,671 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.imagecrawler;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
/*
* IMPORTANT: Make sure that you update crawler4j.properties file and set
* crawler.include_images to true
*/
public class ImageCrawlController {
public static void main(String[] args) throws Exception {
if (args.length < 3) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
System.out.println("\t storageFolder (a folder for storing downloaded images)");
return;
}
String rootFolder = args[0];
int numberOfCrawlers = Integer.parseInt(args[1]);
String storageFolder = args[2];
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(rootFolder);
/*
* Since images are binary content, we need to set this parameter to
* true to make sure they are included in the crawl.
*/
config.setIncludeBinaryContentInCrawling(true);
String[] crawlDomains = new String[] { "http://uci.edu/" };
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
for (String domain : crawlDomains) {
controller.addSeed(domain);
}
ImageCrawler.configure(crawlDomains, storageFolder);
controller.start(ImageCrawler.class, numberOfCrawlers);
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/imagecrawler/ImageCrawlController.java | Java | asf20 | 2,674 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.imagecrawler;
import java.io.File;
import java.util.regex.Pattern;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.BinaryParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.IO;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
/*
* This class shows how you can crawl images on the web and store them in a
* folder. This is just for demonstration purposes and doesn't scale for large
* number of images. For crawling millions of images you would need to store
* downloaded images in a hierarchy of folders
*/
public class ImageCrawler extends WebCrawler {
private static final Pattern filters = Pattern.compile(".*(\\.(css|js|mid|mp2|mp3|mp4|wav|avi|mov|mpeg|ram|m4v|pdf"
+ "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
private static final Pattern imgPatterns = Pattern.compile(".*(\\.(bmp|gif|jpe?g|png|tiff?))$");
private static File storageFolder;
private static String[] crawlDomains;
public static void configure(String[] domain, String storageFolderName) {
ImageCrawler.crawlDomains = domain;
storageFolder = new File(storageFolderName);
if (!storageFolder.exists()) {
storageFolder.mkdirs();
}
}
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
if (filters.matcher(href).matches()) {
return false;
}
if (imgPatterns.matcher(href).matches()) {
return true;
}
for (String domain : crawlDomains) {
if (href.startsWith(domain)) {
return true;
}
}
return false;
}
@Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
// We are only interested in processing images
if (!(page.getParseData() instanceof BinaryParseData)) {
return;
}
if (!imgPatterns.matcher(url).matches()) {
return;
}
// Not interested in very small images
if (page.getContentData().length < 10 * 1024) {
return;
}
// get a unique name for storing this image
String extension = url.substring(url.lastIndexOf("."));
String hashedName = Cryptography.MD5(url) + extension;
// store image
IO.writeBytesToFile(page.getContentData(), storageFolder.getAbsolutePath() + "/" + hashedName);
System.out.println("Stored: " + url);
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/imagecrawler/ImageCrawler.java | Java | asf20 | 3,150 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.basic;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class BasicCrawlController {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
/*
* numberOfCrawlers shows the number of concurrent threads that should
* be initiated for crawling.
*/
int numberOfCrawlers = Integer.parseInt(args[1]);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
/*
* Be polite: Make sure that we don't send more than 1 request per
* second (1000 milliseconds between requests).
*/
config.setPolitenessDelay(1000);
/*
* You can set the maximum crawl depth here. The default value is -1 for
* unlimited depth
*/
config.setMaxDepthOfCrawling(2);
/*
* You can set the maximum number of pages to crawl. The default value
* is -1 for unlimited number of pages
*/
config.setMaxPagesToFetch(1000);
/*
* Do you need to set a proxy? If so, you can use:
* config.setProxyHost("proxyserver.example.com");
* config.setProxyPort(8080);
*
* If your proxy also needs authentication:
* config.setProxyUsername(username); config.getProxyPassword(password);
*/
/*
* This config parameter can be used to set your crawl to be resumable
* (meaning that you can resume the crawl from a previously
* interrupted/crashed crawl). Note: if you enable resuming feature and
* want to start a fresh crawl, you need to delete the contents of
* rootFolder manually.
*/
config.setResumableCrawling(false);
/*
* Instantiate the controller for this crawl.
*/
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
/*
* For each crawl, you need to add some seed urls. These are the first
* URLs that are fetched and then the crawler starts following links
* which are found in these pages
*/
controller.addSeed("http://www.ics.uci.edu/");
controller.addSeed("http://www.ics.uci.edu/~lopes/");
controller.addSeed("http://www.ics.uci.edu/~welling/");
/*
* Start the crawl. This is a blocking operation, meaning that your code
* will reach the line after this only when crawling is finished.
*/
controller.start(BasicCrawler.class, numberOfCrawlers);
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/basic/BasicCrawlController.java | Java | asf20 | 3,948 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.basic;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.http.Header;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class BasicCrawler extends WebCrawler {
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
/**
* You should implement this function to specify whether the given url
* should be crawled or not (based on your crawling logic).
*/
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready to be processed
* by your program.
*/
@Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
String domain = page.getWebURL().getDomain();
String path = page.getWebURL().getPath();
String subDomain = page.getWebURL().getSubDomain();
String parentUrl = page.getWebURL().getParentUrl();
String anchor = page.getWebURL().getAnchor();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Domain: '" + domain + "'");
System.out.println("Sub-domain: '" + subDomain + "'");
System.out.println("Path: '" + path + "'");
System.out.println("Parent page: " + parentUrl);
System.out.println("Anchor text: " + anchor);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
Header[] responseHeaders = page.getFetchResponseHeaders();
if (responseHeaders != null) {
System.out.println("Response headers:");
for (Header header : responseHeaders) {
System.out.println("\t" + header.getName() + ": " + header.getValue());
}
}
System.out.println("=============");
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/basic/BasicCrawler.java | Java | asf20 | 3,349 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.localdata;
import org.apache.http.HttpStatus;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.fetcher.PageFetchResult;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.parser.ParseData;
import edu.uci.ics.crawler4j.parser.Parser;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* This class is a demonstration of how crawler4j can be used to download a
* single page and extract its title and text.
*/
public class Downloader {
private Parser parser;
private PageFetcher pageFetcher;
public Downloader() {
CrawlConfig config = new CrawlConfig();
parser = new Parser(config);
pageFetcher = new PageFetcher(config);
}
private Page download(String url) {
WebURL curURL = new WebURL();
curURL.setURL(url);
PageFetchResult fetchResult = null;
try {
fetchResult = pageFetcher.fetchHeader(curURL);
if (fetchResult.getStatusCode() == HttpStatus.SC_OK) {
try {
Page page = new Page(curURL);
fetchResult.fetchContent(page);
if (parser.parse(page, curURL.getURL())) {
return page;
}
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
if (fetchResult != null)
{
fetchResult.discardContentIfNotConsumed();
}
}
return null;
}
public void processUrl(String url) {
System.out.println("Processing: " + url);
Page page = download(url);
if (page != null) {
ParseData parseData = page.getParseData();
if (parseData != null) {
if (parseData instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) parseData;
System.out.println("Title: " + htmlParseData.getTitle());
System.out.println("Text length: " + htmlParseData.getText().length());
System.out.println("Html length: " + htmlParseData.getHtml().length());
}
} else {
System.out.println("Couldn't parse the content of the page.");
}
} else {
System.out.println("Couldn't fetch the content of the page.");
}
System.out.println("==============");
}
public static void main(String[] args) {
Downloader downloader = new Downloader();
downloader.processUrl("http://en.wikipedia.org/wiki/Main_Page/");
downloader.processUrl("http://www.yahoo.com/");
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/localdata/Downloader.java | Java | asf20 | 3,177 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.localdata;
import java.util.List;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class LocalDataCollectorController {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
return;
}
String rootFolder = args[0];
int numberOfCrawlers = Integer.parseInt(args[1]);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(rootFolder);
config.setMaxPagesToFetch(10);
config.setPolitenessDelay(1000);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
controller.addSeed("http://www.ics.uci.edu/");
controller.start(LocalDataCollectorCrawler.class, numberOfCrawlers);
List<Object> crawlersLocalData = controller.getCrawlersLocalData();
long totalLinks = 0;
long totalTextSize = 0;
int totalProcessedPages = 0;
for (Object localData : crawlersLocalData) {
CrawlStat stat = (CrawlStat) localData;
totalLinks += stat.getTotalLinks();
totalTextSize += stat.getTotalTextSize();
totalProcessedPages += stat.getTotalProcessedPages();
}
System.out.println("Aggregated Statistics:");
System.out.println(" Processed Pages: " + totalProcessedPages);
System.out.println(" Total Links found: " + totalLinks);
System.out.println(" Total Text Size: " + totalTextSize);
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/localdata/LocalDataCollectorController.java | Java | asf20 | 2,776 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.localdata;
public class CrawlStat {
private int totalProcessedPages;
private long totalLinks;
private long totalTextSize;
public int getTotalProcessedPages() {
return totalProcessedPages;
}
public void setTotalProcessedPages(int totalProcessedPages) {
this.totalProcessedPages = totalProcessedPages;
}
public void incProcessedPages() {
this.totalProcessedPages++;
}
public long getTotalLinks() {
return totalLinks;
}
public void setTotalLinks(long totalLinks) {
this.totalLinks = totalLinks;
}
public long getTotalTextSize() {
return totalTextSize;
}
public void setTotalTextSize(long totalTextSize) {
this.totalTextSize = totalTextSize;
}
public void incTotalLinks(int count) {
this.totalLinks += count;
}
public void incTotalTextSize(int count) {
this.totalTextSize += count;
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/localdata/CrawlStat.java | Java | asf20 | 1,675 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.examples.localdata;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Pattern;
public class LocalDataCollectorCrawler extends WebCrawler {
Pattern filters = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
CrawlStat myCrawlStat;
public LocalDataCollectorCrawler() {
myCrawlStat = new CrawlStat();
}
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !filters.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
@Override
public void visit(Page page) {
System.out.println("Visited: " + page.getWebURL().getURL());
myCrawlStat.incProcessedPages();
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData parseData = (HtmlParseData) page.getParseData();
List<WebURL> links = parseData.getOutgoingUrls();
myCrawlStat.incTotalLinks(links.size());
try {
myCrawlStat.incTotalTextSize(parseData.getText().getBytes("UTF-8").length);
} catch (UnsupportedEncodingException ignored) {
// Do nothing
}
}
// We dump this crawler statistics after processing every 50 pages
if (myCrawlStat.getTotalProcessedPages() % 50 == 0) {
dumpMyData();
}
}
// This function is called by controller to get the local data of this
// crawler when job is finished
@Override
public Object getMyLocalData() {
return myCrawlStat;
}
// This function is called by controller before finishing the job.
// You can put whatever stuff you need here.
@Override
public void onBeforeExit() {
dumpMyData();
}
public void dumpMyData() {
int id = getMyId();
// This is just an example. Therefore I print on screen. You may
// probably want to write in a text file.
System.out.println("Crawler " + id + "> Processed Pages: " + myCrawlStat.getTotalProcessedPages());
System.out.println("Crawler " + id + "> Total Links Found: " + myCrawlStat.getTotalLinks());
System.out.println("Crawler " + id + "> Total Text Size: " + myCrawlStat.getTotalTextSize());
}
}
| 12rohhit-rohit | src/test/java/edu/uci/ics/crawler4j/examples/localdata/LocalDataCollectorCrawler.java | Java | asf20 | 3,154 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.crawler;
import java.nio.charset.Charset;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;
import edu.uci.ics.crawler4j.parser.ParseData;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* This class contains the data for a fetched and parsed page.
*
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class Page {
/**
* The URL of this page.
*/
protected WebURL url;
/**
* The content of this page in binary format.
*/
protected byte[] contentData;
/**
* The ContentType of this page.
* For example: "text/html; charset=UTF-8"
*/
protected String contentType;
/**
* The encoding of the content.
* For example: "gzip"
*/
protected String contentEncoding;
/**
* The charset of the content.
* For example: "UTF-8"
*/
protected String contentCharset;
/**
* Headers which were present in the response of the
* fetch request
*/
protected Header[] fetchResponseHeaders;
/**
* The parsed data populated by parsers
*/
protected ParseData parseData;
public Page(WebURL url) {
this.url = url;
}
public WebURL getWebURL() {
return url;
}
public void setWebURL(WebURL url) {
this.url = url;
}
/**
* Loads the content of this page from a fetched
* HttpEntity.
*/
public void load(HttpEntity entity) throws Exception {
contentType = null;
Header type = entity.getContentType();
if (type != null) {
contentType = type.getValue();
}
contentEncoding = null;
Header encoding = entity.getContentEncoding();
if (encoding != null) {
contentEncoding = encoding.getValue();
}
Charset charset = ContentType.getOrDefault(entity).getCharset();
if (charset != null) {
contentCharset = charset.displayName();
}
contentData = EntityUtils.toByteArray(entity);
}
/**
* Returns headers which were present in the response of the
* fetch request
*/
public Header[] getFetchResponseHeaders() {
return fetchResponseHeaders;
}
public void setFetchResponseHeaders(Header[] headers) {
fetchResponseHeaders = headers;
}
/**
* Returns the parsed data generated for this page by parsers
*/
public ParseData getParseData() {
return parseData;
}
public void setParseData(ParseData parseData) {
this.parseData = parseData;
}
/**
* Returns the content of this page in binary format.
*/
public byte[] getContentData() {
return contentData;
}
public void setContentData(byte[] contentData) {
this.contentData = contentData;
}
/**
* Returns the ContentType of this page.
* For example: "text/html; charset=UTF-8"
*/
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
/**
* Returns the encoding of the content.
* For example: "gzip"
*/
public String getContentEncoding() {
return contentEncoding;
}
public void setContentEncoding(String contentEncoding) {
this.contentEncoding = contentEncoding;
}
/**
* Returns the charset of the content.
* For example: "UTF-8"
*/
public String getContentCharset() {
return contentCharset;
}
public void setContentCharset(String contentCharset) {
this.contentCharset = contentCharset;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/crawler/Page.java | Java | asf20 | 4,336 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.crawler;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.frontier.DocIDServer;
import edu.uci.ics.crawler4j.frontier.Frontier;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import edu.uci.ics.crawler4j.url.URLCanonicalizer;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.IO;
import org.apache.log4j.Logger;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* The controller that manages a crawling session. This class creates the
* crawler threads and monitors their progress.
*
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class CrawlController extends Configurable {
static final Logger logger = Logger.getLogger(CrawlController.class.getName());
/**
* The 'customData' object can be used for passing custom crawl-related
* configurations to different components of the crawler.
*/
protected Object customData;
/**
* Once the crawling session finishes the controller collects the local data
* of the crawler threads and stores them in this List.
*/
protected List<Object> crawlersLocalData = new ArrayList<>();
/**
* Is the crawling of this session finished?
*/
protected boolean finished;
/**
* Is the crawling session set to 'shutdown'. Crawler threads monitor this
* flag and when it is set they will no longer process new pages.
*/
protected boolean shuttingDown;
protected PageFetcher pageFetcher;
protected RobotstxtServer robotstxtServer;
protected Frontier frontier;
protected DocIDServer docIdServer;
protected final Object waitingLock = new Object();
public CrawlController(CrawlConfig config, PageFetcher pageFetcher, RobotstxtServer robotstxtServer)
throws Exception {
super(config);
config.validate();
File folder = new File(config.getCrawlStorageFolder());
if (!folder.exists()) {
if (!folder.mkdirs()) {
throw new Exception("Couldn't create this folder: " + folder.getAbsolutePath());
}
}
boolean resumable = config.isResumableCrawling();
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
envConfig.setTransactional(resumable);
envConfig.setLocking(resumable);
File envHome = new File(config.getCrawlStorageFolder() + "/frontier");
if (!envHome.exists()) {
if (!envHome.mkdir()) {
throw new Exception("Couldn't create this folder: " + envHome.getAbsolutePath());
}
}
if (!resumable) {
IO.deleteFolderContents(envHome);
}
Environment env = new Environment(envHome, envConfig);
docIdServer = new DocIDServer(env, config);
frontier = new Frontier(env, config, docIdServer);
this.pageFetcher = pageFetcher;
this.robotstxtServer = robotstxtServer;
finished = false;
shuttingDown = false;
}
/**
* Start the crawling session and wait for it to finish.
*
* @param _c
* the class that implements the logic for crawler threads
* @param numberOfCrawlers
* the number of concurrent threads that will be contributing in
* this crawling session.
*/
public <T extends WebCrawler> void start(final Class<T> _c, final int numberOfCrawlers) {
this.start(_c, numberOfCrawlers, true);
}
/**
* Start the crawling session and return immediately.
*
* @param _c
* the class that implements the logic for crawler threads
* @param numberOfCrawlers
* the number of concurrent threads that will be contributing in
* this crawling session.
*/
public <T extends WebCrawler> void startNonBlocking(final Class<T> _c, final int numberOfCrawlers) {
this.start(_c, numberOfCrawlers, false);
}
protected <T extends WebCrawler> void start(final Class<T> _c, final int numberOfCrawlers, boolean isBlocking) {
try {
finished = false;
crawlersLocalData.clear();
final List<Thread> threads = new ArrayList<>();
final List<T> crawlers = new ArrayList<>();
for (int i = 1; i <= numberOfCrawlers; i++) {
T crawler = _c.newInstance();
Thread thread = new Thread(crawler, "Crawler " + i);
crawler.setThread(thread);
crawler.init(i, this);
thread.start();
crawlers.add(crawler);
threads.add(thread);
logger.info("Crawler " + i + " started.");
}
final CrawlController controller = this;
Thread monitorThread = new Thread(new Runnable() {
@Override
public void run() {
try {
synchronized (waitingLock) {
while (true) {
sleep(10);
boolean someoneIsWorking = false;
for (int i = 0; i < threads.size(); i++) {
Thread thread = threads.get(i);
if (!thread.isAlive()) {
if (!shuttingDown) {
logger.info("Thread " + i + " was dead, I'll recreate it.");
T crawler = _c.newInstance();
thread = new Thread(crawler, "Crawler " + (i + 1));
threads.remove(i);
threads.add(i, thread);
crawler.setThread(thread);
crawler.init(i + 1, controller);
thread.start();
crawlers.remove(i);
crawlers.add(i, crawler);
}
} else if (crawlers.get(i).isNotWaitingForNewURLs()) {
someoneIsWorking = true;
}
}
if (!someoneIsWorking) {
// Make sure again that none of the threads
// are
// alive.
logger.info("It looks like no thread is working, waiting for 10 seconds to make sure...");
sleep(10);
someoneIsWorking = false;
for (int i = 0; i < threads.size(); i++) {
Thread thread = threads.get(i);
if (thread.isAlive() && crawlers.get(i).isNotWaitingForNewURLs()) {
someoneIsWorking = true;
}
}
if (!someoneIsWorking) {
if (!shuttingDown) {
long queueLength = frontier.getQueueLength();
if (queueLength > 0) {
continue;
}
logger.info("No thread is working and no more URLs are in queue waiting for another 10 seconds to make sure...");
sleep(10);
queueLength = frontier.getQueueLength();
if (queueLength > 0) {
continue;
}
}
logger.info("All of the crawlers are stopped. Finishing the process...");
// At this step, frontier notifies the
// threads that were
// waiting for new URLs and they should
// stop
frontier.finish();
for (T crawler : crawlers) {
crawler.onBeforeExit();
crawlersLocalData.add(crawler.getMyLocalData());
}
logger.info("Waiting for 10 seconds before final clean up...");
sleep(10);
frontier.close();
docIdServer.close();
pageFetcher.shutDown();
finished = true;
waitingLock.notifyAll();
return;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
monitorThread.start();
if (isBlocking) {
waitUntilFinish();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Wait until this crawling session finishes.
*/
public void waitUntilFinish() {
while (!finished) {
synchronized (waitingLock) {
if (finished) {
return;
}
try {
waitingLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* Once the crawling session finishes the controller collects the local data
* of the crawler threads and stores them in a List. This function returns
* the reference to this list.
*/
public List<Object> getCrawlersLocalData() {
return crawlersLocalData;
}
protected static void sleep(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (Exception ignored) {
// Do nothing
}
}
/**
* Adds a new seed URL. A seed URL is a URL that is fetched by the crawler
* to extract new URLs in it and follow them for crawling.
*
* @param pageUrl
* the URL of the seed
*/
public void addSeed(String pageUrl) {
addSeed(pageUrl, -1);
}
/**
* Adds a new seed URL. A seed URL is a URL that is fetched by the crawler
* to extract new URLs in it and follow them for crawling. You can also
* specify a specific document id to be assigned to this seed URL. This
* document id needs to be unique. Also, note that if you add three seeds
* with document ids 1,2, and 7. Then the next URL that is found during the
* crawl will get a doc id of 8. Also you need to ensure to add seeds in
* increasing order of document ids.
*
* Specifying doc ids is mainly useful when you have had a previous crawl
* and have stored the results and want to start a new crawl with seeds
* which get the same document ids as the previous crawl.
*
* @param pageUrl
* the URL of the seed
* @param docId
* the document id that you want to be assigned to this seed URL.
*
*/
public void addSeed(String pageUrl, int docId) {
String canonicalUrl = URLCanonicalizer.getCanonicalURL(pageUrl);
if (canonicalUrl == null) {
logger.error("Invalid seed URL: " + pageUrl);
return;
}
if (docId < 0) {
docId = docIdServer.getDocId(canonicalUrl);
if (docId > 0) {
// This URL is already seen.
return;
}
docId = docIdServer.getNewDocID(canonicalUrl);
} else {
try {
docIdServer.addUrlAndDocId(canonicalUrl, docId);
} catch (Exception e) {
logger.error("Could not add seed: " + e.getMessage());
}
}
WebURL webUrl = new WebURL();
webUrl.setURL(canonicalUrl);
webUrl.setDocid(docId);
webUrl.setDepth((short) 0);
if (!robotstxtServer.allows(webUrl)) {
logger.info("Robots.txt does not allow this seed: " + pageUrl);
} else {
frontier.schedule(webUrl);
}
}
/**
* This function can called to assign a specific document id to a url. This
* feature is useful when you have had a previous crawl and have stored the
* Urls and their associated document ids and want to have a new crawl which
* is aware of the previously seen Urls and won't re-crawl them.
*
* Note that if you add three seen Urls with document ids 1,2, and 7. Then
* the next URL that is found during the crawl will get a doc id of 8. Also
* you need to ensure to add seen Urls in increasing order of document ids.
*
* @param url
* the URL of the page
* @param docId
* the document id that you want to be assigned to this URL.
*
*/
public void addSeenUrl(String url, int docId) {
String canonicalUrl = URLCanonicalizer.getCanonicalURL(url);
if (canonicalUrl == null) {
logger.error("Invalid Url: " + url);
return;
}
try {
docIdServer.addUrlAndDocId(canonicalUrl, docId);
} catch (Exception e) {
logger.error("Could not add seen url: " + e.getMessage());
}
}
public PageFetcher getPageFetcher() {
return pageFetcher;
}
public void setPageFetcher(PageFetcher pageFetcher) {
this.pageFetcher = pageFetcher;
}
public RobotstxtServer getRobotstxtServer() {
return robotstxtServer;
}
public void setRobotstxtServer(RobotstxtServer robotstxtServer) {
this.robotstxtServer = robotstxtServer;
}
public Frontier getFrontier() {
return frontier;
}
public void setFrontier(Frontier frontier) {
this.frontier = frontier;
}
public DocIDServer getDocIdServer() {
return docIdServer;
}
public void setDocIdServer(DocIDServer docIdServer) {
this.docIdServer = docIdServer;
}
public Object getCustomData() {
return customData;
}
public void setCustomData(Object customData) {
this.customData = customData;
}
public boolean isFinished() {
return this.finished;
}
public boolean isShuttingDown() {
return shuttingDown;
}
/**
* Set the current crawling session set to 'shutdown'. Crawler threads
* monitor the shutdown flag and when it is set to true, they will no longer
* process new pages.
*/
public void shutdown() {
logger.info("Shutting down...");
this.shuttingDown = true;
frontier.finish();
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/crawler/CrawlController.java | Java | asf20 | 13,014 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.crawler;
/**
* Several core components of crawler4j extend this class
* to make them configurable.
*
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public abstract class Configurable {
protected CrawlConfig config;
protected Configurable(CrawlConfig config) {
this.config = config;
}
public CrawlConfig getConfig() {
return config;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/crawler/Configurable.java | Java | asf20 | 1,203 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.crawler;
public class CrawlConfig {
/**
* The folder which will be used by crawler for storing the intermediate
* crawl data. The content of this folder should not be modified manually.
*/
private String crawlStorageFolder;
/**
* If this feature is enabled, you would be able to resume a previously
* stopped/crashed crawl. However, it makes crawling slightly slower
*/
private boolean resumableCrawling = false;
/**
* Maximum depth of crawling For unlimited depth this parameter should be
* set to -1
*/
private int maxDepthOfCrawling = -1;
/**
* Maximum number of pages to fetch For unlimited number of pages, this
* parameter should be set to -1
*/
private int maxPagesToFetch = -1;
/**
* user-agent string that is used for representing your crawler to web
* servers. See http://en.wikipedia.org/wiki/User_agent for more details
*/
private String userAgentString = "crawler4j (http://code.google.com/p/crawler4j/)";
/**
* Politeness delay in milliseconds (delay between sending two requests to
* the same host).
*/
private int politenessDelay = 200;
/**
* Should we also crawl https pages?
*/
private boolean includeHttpsPages = false;
/**
* Should we fetch binary content such as images, audio, ...?
*/
private boolean includeBinaryContentInCrawling = false;
/**
* Maximum Connections per host
*/
private int maxConnectionsPerHost = 100;
/**
* Maximum total connections
*/
private int maxTotalConnections = 100;
/**
* Socket timeout in milliseconds
*/
private int socketTimeout = 20000;
/**
* Connection timeout in milliseconds
*/
private int connectionTimeout = 30000;
/**
* Max number of outgoing links which are processed from a page
*/
private int maxOutgoingLinksToFollow = 5000;
/**
* Max allowed size of a page. Pages larger than this size will not be
* fetched.
*/
private int maxDownloadSize = 1048576;
/**
* Should we follow redirects?
*/
private boolean followRedirects = true;
/**
* If crawler should run behind a proxy, this parameter can be used for
* specifying the proxy host.
*/
private String proxyHost = null;
/**
* If crawler should run behind a proxy, this parameter can be used for
* specifying the proxy port.
*/
private int proxyPort = 80;
/**
* If crawler should run behind a proxy and user/pass is needed for
* authentication in proxy, this parameter can be used for specifying the
* username.
*/
private String proxyUsername = null;
/**
* If crawler should run behind a proxy and user/pass is needed for
* authentication in proxy, this parameter can be used for specifying the
* password.
*/
private String proxyPassword = null;
public CrawlConfig() {
}
/**
* Validates the configs specified by this instance.
*
* @throws Exception
*/
public void validate() throws Exception {
if (crawlStorageFolder == null) {
throw new Exception("Crawl storage folder is not set in the CrawlConfig.");
}
if (politenessDelay < 0) {
throw new Exception("Invalid value for politeness delay: " + politenessDelay);
}
if (maxDepthOfCrawling < -1) {
throw new Exception("Maximum crawl depth should be either a positive number or -1 for unlimited depth.");
}
if (maxDepthOfCrawling > Short.MAX_VALUE) {
throw new Exception("Maximum value for crawl depth is " + Short.MAX_VALUE);
}
}
public String getCrawlStorageFolder() {
return crawlStorageFolder;
}
/**
* The folder which will be used by crawler for storing the intermediate
* crawl data. The content of this folder should not be modified manually.
*/
public void setCrawlStorageFolder(String crawlStorageFolder) {
this.crawlStorageFolder = crawlStorageFolder;
}
public boolean isResumableCrawling() {
return resumableCrawling;
}
/**
* If this feature is enabled, you would be able to resume a previously
* stopped/crashed crawl. However, it makes crawling slightly slower
*/
public void setResumableCrawling(boolean resumableCrawling) {
this.resumableCrawling = resumableCrawling;
}
public int getMaxDepthOfCrawling() {
return maxDepthOfCrawling;
}
/**
* Maximum depth of crawling For unlimited depth this parameter should be
* set to -1
*/
public void setMaxDepthOfCrawling(int maxDepthOfCrawling) {
this.maxDepthOfCrawling = maxDepthOfCrawling;
}
public int getMaxPagesToFetch() {
return maxPagesToFetch;
}
/**
* Maximum number of pages to fetch For unlimited number of pages, this
* parameter should be set to -1
*/
public void setMaxPagesToFetch(int maxPagesToFetch) {
this.maxPagesToFetch = maxPagesToFetch;
}
public String getUserAgentString() {
return userAgentString;
}
/**
* user-agent string that is used for representing your crawler to web
* servers. See http://en.wikipedia.org/wiki/User_agent for more details
*/
public void setUserAgentString(String userAgentString) {
this.userAgentString = userAgentString;
}
public int getPolitenessDelay() {
return politenessDelay;
}
/**
* Politeness delay in milliseconds (delay between sending two requests to
* the same host).
*
* @param politenessDelay
* the delay in milliseconds.
*/
public void setPolitenessDelay(int politenessDelay) {
this.politenessDelay = politenessDelay;
}
public boolean isIncludeHttpsPages() {
return includeHttpsPages;
}
/**
* Should we also crawl https pages?
*/
public void setIncludeHttpsPages(boolean includeHttpsPages) {
this.includeHttpsPages = includeHttpsPages;
}
public boolean isIncludeBinaryContentInCrawling() {
return includeBinaryContentInCrawling;
}
/**
* Should we fetch binary content such as images, audio, ...?
*/
public void setIncludeBinaryContentInCrawling(boolean includeBinaryContentInCrawling) {
this.includeBinaryContentInCrawling = includeBinaryContentInCrawling;
}
public int getMaxConnectionsPerHost() {
return maxConnectionsPerHost;
}
/**
* Maximum Connections per host
*/
public void setMaxConnectionsPerHost(int maxConnectionsPerHost) {
this.maxConnectionsPerHost = maxConnectionsPerHost;
}
public int getMaxTotalConnections() {
return maxTotalConnections;
}
/**
* Maximum total connections
*/
public void setMaxTotalConnections(int maxTotalConnections) {
this.maxTotalConnections = maxTotalConnections;
}
public int getSocketTimeout() {
return socketTimeout;
}
/**
* Socket timeout in milliseconds
*/
public void setSocketTimeout(int socketTimeout) {
this.socketTimeout = socketTimeout;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
/**
* Connection timeout in milliseconds
*/
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public int getMaxOutgoingLinksToFollow() {
return maxOutgoingLinksToFollow;
}
/**
* Max number of outgoing links which are processed from a page
*/
public void setMaxOutgoingLinksToFollow(int maxOutgoingLinksToFollow) {
this.maxOutgoingLinksToFollow = maxOutgoingLinksToFollow;
}
public int getMaxDownloadSize() {
return maxDownloadSize;
}
/**
* Max allowed size of a page. Pages larger than this size will not be
* fetched.
*/
public void setMaxDownloadSize(int maxDownloadSize) {
this.maxDownloadSize = maxDownloadSize;
}
public boolean isFollowRedirects() {
return followRedirects;
}
/**
* Should we follow redirects?
*/
public void setFollowRedirects(boolean followRedirects) {
this.followRedirects = followRedirects;
}
public String getProxyHost() {
return proxyHost;
}
/**
* If crawler should run behind a proxy, this parameter can be used for
* specifying the proxy host.
*/
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public int getProxyPort() {
return proxyPort;
}
/**
* If crawler should run behind a proxy, this parameter can be used for
* specifying the proxy port.
*/
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
}
public String getProxyUsername() {
return proxyUsername;
}
/**
* If crawler should run behind a proxy and user/pass is needed for
* authentication in proxy, this parameter can be used for specifying the
* username.
*/
public void setProxyUsername(String proxyUsername) {
this.proxyUsername = proxyUsername;
}
public String getProxyPassword() {
return proxyPassword;
}
/**
* If crawler should run behind a proxy and user/pass is needed for
* authentication in proxy, this parameter can be used for specifying the
* password.
*/
public void setProxyPassword(String proxyPassword) {
this.proxyPassword = proxyPassword;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Crawl storage folder: " + getCrawlStorageFolder() + "\n");
sb.append("Resumable crawling: " + isResumableCrawling() + "\n");
sb.append("Max depth of crawl: " + getMaxDepthOfCrawling() + "\n");
sb.append("Max pages to fetch: " + getMaxPagesToFetch() + "\n");
sb.append("User agent string: " + getUserAgentString() + "\n");
sb.append("Include https pages: " + isIncludeHttpsPages() + "\n");
sb.append("Include binary content: " + isIncludeBinaryContentInCrawling() + "\n");
sb.append("Max connections per host: " + getMaxConnectionsPerHost() + "\n");
sb.append("Max total connections: " + getMaxTotalConnections() + "\n");
sb.append("Socket timeout: " + getSocketTimeout() + "\n");
sb.append("Max total connections: " + getMaxTotalConnections() + "\n");
sb.append("Max outgoing links to follow: " + getMaxOutgoingLinksToFollow() + "\n");
sb.append("Max download size: " + getMaxDownloadSize() + "\n");
sb.append("Should follow redirects?: " + isFollowRedirects() + "\n");
sb.append("Proxy host: " + getProxyHost() + "\n");
sb.append("Proxy port: " + getProxyPort() + "\n");
sb.append("Proxy username: " + getProxyUsername() + "\n");
sb.append("Proxy password: " + getProxyPassword() + "\n");
return sb.toString();
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/crawler/CrawlConfig.java | Java | asf20 | 10,898 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.crawler;
import edu.uci.ics.crawler4j.fetcher.PageFetchResult;
import edu.uci.ics.crawler4j.fetcher.CustomFetchStatus;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.frontier.DocIDServer;
import edu.uci.ics.crawler4j.frontier.Frontier;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.parser.ParseData;
import edu.uci.ics.crawler4j.parser.Parser;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import edu.uci.ics.crawler4j.url.WebURL;
import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
/**
* WebCrawler class in the Runnable class that is executed by each crawler
* thread.
*
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class WebCrawler implements Runnable {
protected static final Logger logger = Logger.getLogger(WebCrawler.class.getName());
/**
* The id associated to the crawler thread running this instance
*/
protected int myId;
/**
* The controller instance that has created this crawler thread. This
* reference to the controller can be used for getting configurations of the
* current crawl or adding new seeds during runtime.
*/
protected CrawlController myController;
/**
* The thread within which this crawler instance is running.
*/
private Thread myThread;
/**
* The parser that is used by this crawler instance to parse the content of
* the fetched pages.
*/
private Parser parser;
/**
* The fetcher that is used by this crawler instance to fetch the content of
* pages from the web.
*/
private PageFetcher pageFetcher;
/**
* The RobotstxtServer instance that is used by this crawler instance to
* determine whether the crawler is allowed to crawl the content of each
* page.
*/
private RobotstxtServer robotstxtServer;
/**
* The DocIDServer that is used by this crawler instance to map each URL to
* a unique docid.
*/
private DocIDServer docIdServer;
/**
* The Frontier object that manages the crawl queue.
*/
private Frontier frontier;
/**
* Is the current crawler instance waiting for new URLs? This field is
* mainly used by the controller to detect whether all of the crawler
* instances are waiting for new URLs and therefore there is no more work
* and crawling can be stopped.
*/
private boolean isWaitingForNewURLs;
/**
* Initializes the current instance of the crawler
*
* @param id
* the id of this crawler instance
* @param crawlController
* the controller that manages this crawling session
*/
public void init(int id, CrawlController crawlController) {
this.myId = id;
this.pageFetcher = crawlController.getPageFetcher();
this.robotstxtServer = crawlController.getRobotstxtServer();
this.docIdServer = crawlController.getDocIdServer();
this.frontier = crawlController.getFrontier();
this.parser = new Parser(crawlController.getConfig());
this.myController = crawlController;
this.isWaitingForNewURLs = false;
}
/**
* Get the id of the current crawler instance
*
* @return the id of the current crawler instance
*/
public int getMyId() {
return myId;
}
public CrawlController getMyController() {
return myController;
}
/**
* This function is called just before starting the crawl by this crawler
* instance. It can be used for setting up the data structures or
* initializations needed by this crawler instance.
*/
public void onStart() {
// Do nothing by default
// Sub-classed can override this to add their custom functionality
}
/**
* This function is called just before the termination of the current
* crawler instance. It can be used for persisting in-memory data or other
* finalization tasks.
*/
public void onBeforeExit() {
// Do nothing by default
// Sub-classed can override this to add their custom functionality
}
/**
* This function is called once the header of a page is fetched. It can be
* overwritten by sub-classes to perform custom logic for different status
* codes. For example, 404 pages can be logged, etc.
*
* @param webUrl
* @param statusCode
* @param statusDescription
*/
protected void handlePageStatusCode(WebURL webUrl, int statusCode, String statusDescription) {
// Do nothing by default
// Sub-classed can override this to add their custom functionality
}
/**
* This function is called if the content of a url could not be fetched.
*
* @param webUrl
*/
protected void onContentFetchError(WebURL webUrl) {
// Do nothing by default
// Sub-classed can override this to add their custom functionality
}
/**
* This function is called if there has been an error in parsing the
* content.
*
* @param webUrl
*/
protected void onParseError(WebURL webUrl) {
// Do nothing by default
// Sub-classed can override this to add their custom functionality
}
/**
* The CrawlController instance that has created this crawler instance will
* call this function just before terminating this crawler thread. Classes
* that extend WebCrawler can override this function to pass their local
* data to their controller. The controller then puts these local data in a
* List that can then be used for processing the local data of crawlers (if
* needed).
*/
public Object getMyLocalData() {
return null;
}
public void run() {
onStart();
while (true) {
List<WebURL> assignedURLs = new ArrayList<>(50);
isWaitingForNewURLs = true;
frontier.getNextURLs(50, assignedURLs);
isWaitingForNewURLs = false;
if (assignedURLs.size() == 0) {
if (frontier.isFinished()) {
return;
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
for (WebURL curURL : assignedURLs) {
if (curURL != null) {
processPage(curURL);
frontier.setProcessed(curURL);
}
if (myController.isShuttingDown()) {
logger.info("Exiting because of controller shutdown.");
return;
}
}
}
}
}
/**
* Classes that extends WebCrawler can overwrite this function to tell the
* crawler whether the given url should be crawled or not. The following
* implementation indicates that all urls should be included in the crawl.
*
* @param url
* the url which we are interested to know whether it should be
* included in the crawl or not.
* @return if the url should be included in the crawl it returns true,
* otherwise false is returned.
*/
public boolean shouldVisit(WebURL url) {
return true;
}
/**
* Classes that extends WebCrawler can overwrite this function to process
* the content of the fetched and parsed page.
*
* @param page
* the page object that is just fetched and parsed.
*/
public void visit(Page page) {
// Do nothing by default
// Sub-classed can override this to add their custom functionality
}
private void processPage(WebURL curURL) {
if (curURL == null) {
return;
}
PageFetchResult fetchResult = null;
try {
fetchResult = pageFetcher.fetchHeader(curURL);
int statusCode = fetchResult.getStatusCode();
handlePageStatusCode(curURL, statusCode, CustomFetchStatus.getStatusDescription(statusCode));
if (statusCode != HttpStatus.SC_OK) {
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
if (myController.getConfig().isFollowRedirects()) {
String movedToUrl = fetchResult.getMovedToUrl();
if (movedToUrl == null) {
return;
}
int newDocId = docIdServer.getDocId(movedToUrl);
if (newDocId > 0) {
// Redirect page is already seen
return;
}
WebURL webURL = new WebURL();
webURL.setURL(movedToUrl);
webURL.setParentDocid(curURL.getParentDocid());
webURL.setParentUrl(curURL.getParentUrl());
webURL.setDepth(curURL.getDepth());
webURL.setDocid(-1);
webURL.setAnchor(curURL.getAnchor());
if (shouldVisit(webURL) && robotstxtServer.allows(webURL)) {
webURL.setDocid(docIdServer.getNewDocID(movedToUrl));
frontier.schedule(webURL);
}
}
} else if (fetchResult.getStatusCode() == CustomFetchStatus.PageTooBig) {
logger.info("Skipping a page which was bigger than max allowed size: " + curURL.getURL());
}
return;
}
if (!curURL.getURL().equals(fetchResult.getFetchedUrl())) {
if (docIdServer.isSeenBefore(fetchResult.getFetchedUrl())) {
// Redirect page is already seen
return;
}
curURL.setURL(fetchResult.getFetchedUrl());
curURL.setDocid(docIdServer.getNewDocID(fetchResult.getFetchedUrl()));
}
Page page = new Page(curURL);
int docid = curURL.getDocid();
if (!fetchResult.fetchContent(page)) {
onContentFetchError(curURL);
return;
}
if (!parser.parse(page, curURL.getURL())) {
onParseError(curURL);
return;
}
ParseData parseData = page.getParseData();
if (parseData instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) parseData;
List<WebURL> toSchedule = new ArrayList<>();
int maxCrawlDepth = myController.getConfig().getMaxDepthOfCrawling();
for (WebURL webURL : htmlParseData.getOutgoingUrls()) {
webURL.setParentDocid(docid);
webURL.setParentUrl(curURL.getURL());
int newdocid = docIdServer.getDocId(webURL.getURL());
if (newdocid > 0) {
// This is not the first time that this Url is
// visited. So, we set the depth to a negative
// number.
webURL.setDepth((short) -1);
webURL.setDocid(newdocid);
} else {
webURL.setDocid(-1);
webURL.setDepth((short) (curURL.getDepth() + 1));
if (maxCrawlDepth == -1 || curURL.getDepth() < maxCrawlDepth) {
if (shouldVisit(webURL) && robotstxtServer.allows(webURL)) {
webURL.setDocid(docIdServer.getNewDocID(webURL.getURL()));
toSchedule.add(webURL);
}
}
}
}
frontier.scheduleAll(toSchedule);
}
try {
visit(page);
} catch (Exception e) {
logger.error("Exception while running the visit method. Message: '" + e.getMessage() + "' at " + e.getStackTrace()[0]);
}
} catch (Exception e) {
logger.error(e.getMessage() + ", while processing: " + curURL.getURL());
} finally {
if (fetchResult != null) {
fetchResult.discardContentIfNotConsumed();
}
}
}
public Thread getThread() {
return myThread;
}
public void setThread(Thread myThread) {
this.myThread = myThread;
}
public boolean isNotWaitingForNewURLs() {
return !isWaitingForNewURLs;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/crawler/WebCrawler.java | Java | asf20 | 11,522 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.util;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class Util {
public static byte[] long2ByteArray(long l) {
byte[] array = new byte[8];
int i, shift;
for(i = 0, shift = 56; i < 8; i++, shift -= 8) {
array[i] = (byte)(0xFF & (l >> shift));
}
return array;
}
public static byte[] int2ByteArray(int value) {
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
int offset = (3 - i) * 8;
b[i] = (byte) ((value >>> offset) & 0xFF);
}
return b;
}
public static void putIntInByteArray(int value, byte[] buf, int offset) {
for (int i = 0; i < 4; i++) {
int valueOffset = (3 - i) * 8;
buf[offset + i] = (byte) ((value >>> valueOffset) & 0xFF);
}
}
public static int byteArray2Int(byte[] b) {
int value = 0;
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
value += (b[i] & 0x000000FF) << shift;
}
return value;
}
public static long byteArray2Long(byte[] b) {
int value = 0;
for (int i = 0; i < 8; i++) {
int shift = (8 - 1 - i) * 8;
value += (b[i] & 0x000000FF) << shift;
}
return value;
}
public static boolean hasBinaryContent(String contentType) {
if (contentType != null) {
String typeStr = contentType.toLowerCase();
if (typeStr.contains("image") || typeStr.contains("audio") || typeStr.contains("video") || typeStr.contains("application")) {
return true;
}
}
return false;
}
public static boolean hasPlainTextContent(String contentType) {
if (contentType != null) {
String typeStr = contentType.toLowerCase();
if (typeStr.contains("text/plain")) {
return true;
}
}
return false;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/util/Util.java | Java | asf20 | 2,746 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.util;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class IO {
public static boolean deleteFolder(File folder) {
return deleteFolderContents(folder) && folder.delete();
}
public static boolean deleteFolderContents(File folder) {
System.out.println("Deleting content of: " + folder.getAbsolutePath());
File[] files = folder.listFiles();
for (File file : files) {
if (file.isFile()) {
if (!file.delete()) {
return false;
}
} else {
if (!deleteFolder(file)) {
return false;
}
}
}
return true;
}
public static void writeBytesToFile(byte[] bytes, String destination) {
try {
FileChannel fc = new FileOutputStream(destination).getChannel();
fc.write(ByteBuffer.wrap(bytes));
fc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/util/IO.java | Java | asf20 | 1,755 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.robotstxt;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpStatus;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.fetcher.PageFetchResult;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.Util;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class RobotstxtServer {
protected RobotstxtConfig config;
protected final Map<String, HostDirectives> host2directivesCache = new HashMap<>();
protected PageFetcher pageFetcher;
public RobotstxtServer(RobotstxtConfig config, PageFetcher pageFetcher) {
this.config = config;
this.pageFetcher = pageFetcher;
}
private static String getHost(URL url) {
return url.getHost().toLowerCase();
}
public boolean allows(WebURL webURL) {
if (!config.isEnabled()) {
return true;
}
try {
URL url = new URL(webURL.getURL());
String host = getHost(url);
String path = url.getPath();
HostDirectives directives = host2directivesCache.get(host);
if (directives != null && directives.needsRefetch()) {
synchronized (host2directivesCache) {
host2directivesCache.remove(host);
directives = null;
}
}
if (directives == null) {
directives = fetchDirectives(url);
}
return directives.allows(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return true;
}
private HostDirectives fetchDirectives(URL url) {
WebURL robotsTxtUrl = new WebURL();
String host = getHost(url);
String port = (url.getPort() == url.getDefaultPort() || url.getPort() == -1) ? "" : ":" + url.getPort();
robotsTxtUrl.setURL("http://" + host + port + "/robots.txt");
HostDirectives directives = null;
PageFetchResult fetchResult = null;
try {
fetchResult = pageFetcher.fetchHeader(robotsTxtUrl);
if (fetchResult.getStatusCode() == HttpStatus.SC_OK) {
Page page = new Page(robotsTxtUrl);
fetchResult.fetchContent(page);
if (Util.hasPlainTextContent(page.getContentType())) {
try {
String content;
if (page.getContentCharset() == null) {
content = new String(page.getContentData());
} else {
content = new String(page.getContentData(), page.getContentCharset());
}
directives = RobotstxtParser.parse(content, config.getUserAgentName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
} finally {
if (fetchResult != null) {
fetchResult.discardContentIfNotConsumed();
}
}
if (directives == null) {
// We still need to have this object to keep track of the time we
// fetched it
directives = new HostDirectives();
}
synchronized (host2directivesCache) {
if (host2directivesCache.size() == config.getCacheSize()) {
String minHost = null;
long minAccessTime = Long.MAX_VALUE;
for (Entry<String, HostDirectives> entry : host2directivesCache.entrySet()) {
if (entry.getValue().getLastAccessTime() < minAccessTime) {
minAccessTime = entry.getValue().getLastAccessTime();
minHost = entry.getKey();
}
}
host2directivesCache.remove(minHost);
}
host2directivesCache.put(host, directives);
}
return directives;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/robotstxt/RobotstxtServer.java | Java | asf20 | 4,167 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.robotstxt;
import java.util.StringTokenizer;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class RobotstxtParser {
private static final String PATTERNS_USERAGENT = "(?i)^User-agent:.*";
private static final String PATTERNS_DISALLOW = "(?i)Disallow:.*";
private static final String PATTERNS_ALLOW = "(?i)Allow:.*";
private static final int PATTERNS_USERAGENT_LENGTH = 11;
private static final int PATTERNS_DISALLOW_LENGTH = 9;
private static final int PATTERNS_ALLOW_LENGTH = 6;
public static HostDirectives parse(String content, String myUserAgent) {
HostDirectives directives = null;
boolean inMatchingUserAgent = false;
StringTokenizer st = new StringTokenizer(content, "\n");
while (st.hasMoreTokens()) {
String line = st.nextToken();
int commentIndex = line.indexOf("#");
if (commentIndex > -1) {
line = line.substring(0, commentIndex);
}
// remove any html markup
line = line.replaceAll("<[^>]+>", "");
line = line.trim();
if (line.length() == 0) {
continue;
}
if (line.matches(PATTERNS_USERAGENT)) {
String ua = line.substring(PATTERNS_USERAGENT_LENGTH).trim().toLowerCase();
if (ua.equals("*") || ua.contains(myUserAgent)) {
inMatchingUserAgent = true;
} else {
inMatchingUserAgent = false;
}
} else if (line.matches(PATTERNS_DISALLOW)) {
if (!inMatchingUserAgent) {
continue;
}
String path = line.substring(PATTERNS_DISALLOW_LENGTH).trim();
if (path.endsWith("*")) {
path = path.substring(0, path.length() - 1);
}
path = path.trim();
if (path.length() > 0) {
if (directives == null) {
directives = new HostDirectives();
}
directives.addDisallow(path);
}
} else if (line.matches(PATTERNS_ALLOW)) {
if (!inMatchingUserAgent) {
continue;
}
String path = line.substring(PATTERNS_ALLOW_LENGTH).trim();
if (path.endsWith("*")) {
path = path.substring(0, path.length() - 1);
}
path = path.trim();
if (directives == null) {
directives = new HostDirectives();
}
directives.addAllow(path);
}
}
return directives;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/robotstxt/RobotstxtParser.java | Java | asf20 | 3,032 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.robotstxt;
import java.util.SortedSet;
import java.util.TreeSet;
public class RuleSet extends TreeSet<String> {
private static final long serialVersionUID = 1L;
@Override
public boolean add(String str) {
SortedSet<String> sub = headSet(str);
if (!sub.isEmpty() && str.startsWith(sub.last())) {
// no need to add; prefix is already present
return false;
}
boolean retVal = super.add(str);
sub = tailSet(str + "\0");
while (!sub.isEmpty() && sub.first().startsWith(str)) {
// remove redundant entries
sub.remove(sub.first());
}
return retVal;
}
public boolean containsPrefixOf(String s) {
SortedSet<String> sub = headSet(s);
// because redundant prefixes have been eliminated,
// only a test against last item in headSet is necessary
if (!sub.isEmpty() && s.startsWith(sub.last())) {
return true; // prefix substring exists
}
// might still exist exactly (headSet does not contain boundary)
return contains(s);
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/robotstxt/RuleSet.java | Java | asf20 | 1,806 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.robotstxt;
public class RobotstxtConfig {
/**
* Should the crawler obey Robots.txt protocol? More info on Robots.txt is
* available at http://www.robotstxt.org/
*/
private boolean enabled = true;
/**
* user-agent name that will be used to determine whether some servers have
* specific rules for this agent name.
*/
private String userAgentName = "crawler4j";
/**
* The maximum number of hosts for which their robots.txt is cached.
*/
private int cacheSize = 500;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getUserAgentName() {
return userAgentName;
}
public void setUserAgentName(String userAgentName) {
this.userAgentName = userAgentName;
}
public int getCacheSize() {
return cacheSize;
}
public void setCacheSize(int cacheSize) {
this.cacheSize = cacheSize;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/robotstxt/RobotstxtConfig.java | Java | asf20 | 1,742 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.robotstxt;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class HostDirectives {
// If we fetched the directives for this host more than
// 24 hours, we have to re-fetch it.
private static final long EXPIRATION_DELAY = 24 * 60 * 1000L;
private RuleSet disallows = new RuleSet();
private RuleSet allows = new RuleSet();
private long timeFetched;
private long timeLastAccessed;
public HostDirectives() {
timeFetched = System.currentTimeMillis();
}
public boolean needsRefetch() {
return (System.currentTimeMillis() - timeFetched > EXPIRATION_DELAY);
}
public boolean allows(String path) {
timeLastAccessed = System.currentTimeMillis();
return !disallows.containsPrefixOf(path) || allows.containsPrefixOf(path);
}
public void addDisallow(String path) {
disallows.add(path);
}
public void addAllow(String path) {
allows.add(path);
}
public long getLastAccessTime() {
return timeLastAccessed;
}
} | 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/robotstxt/HostDirectives.java | Java | asf20 | 1,804 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.frontier;
import com.sleepycat.je.*;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.Util;
import java.util.ArrayList;
import java.util.List;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class WorkQueues {
protected Database urlsDB = null;
protected Environment env;
protected boolean resumable;
protected WebURLTupleBinding webURLBinding;
protected final Object mutex = new Object();
public WorkQueues(Environment env, String dbName, boolean resumable) throws DatabaseException {
this.env = env;
this.resumable = resumable;
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
dbConfig.setTransactional(resumable);
dbConfig.setDeferredWrite(!resumable);
urlsDB = env.openDatabase(null, dbName, dbConfig);
webURLBinding = new WebURLTupleBinding();
}
public List<WebURL> get(int max) throws DatabaseException {
synchronized (mutex) {
int matches = 0;
List<WebURL> results = new ArrayList<>(max);
Cursor cursor = null;
OperationStatus result;
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry value = new DatabaseEntry();
Transaction txn;
if (resumable) {
txn = env.beginTransaction(null, null);
} else {
txn = null;
}
try {
cursor = urlsDB.openCursor(txn, null);
result = cursor.getFirst(key, value, null);
while (matches < max && result == OperationStatus.SUCCESS) {
if (value.getData().length > 0) {
results.add(webURLBinding.entryToObject(value));
matches++;
}
result = cursor.getNext(key, value, null);
}
} catch (DatabaseException e) {
if (txn != null) {
txn.abort();
txn = null;
}
throw e;
} finally {
if (cursor != null) {
cursor.close();
}
if (txn != null) {
txn.commit();
}
}
return results;
}
}
public void delete(int count) throws DatabaseException {
synchronized (mutex) {
int matches = 0;
Cursor cursor = null;
OperationStatus result;
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry value = new DatabaseEntry();
Transaction txn;
if (resumable) {
txn = env.beginTransaction(null, null);
} else {
txn = null;
}
try {
cursor = urlsDB.openCursor(txn, null);
result = cursor.getFirst(key, value, null);
while (matches < count && result == OperationStatus.SUCCESS) {
cursor.delete();
matches++;
result = cursor.getNext(key, value, null);
}
} catch (DatabaseException e) {
if (txn != null) {
txn.abort();
txn = null;
}
throw e;
} finally {
if (cursor != null) {
cursor.close();
}
if (txn != null) {
txn.commit();
}
}
}
}
/*
* The key that is used for storing URLs determines the order
* they are crawled. Lower key values results in earlier crawling.
* Here our keys are 6 bytes. The first byte comes from the URL priority.
* The second byte comes from depth of crawl at which this URL is first found.
* The rest of the 4 bytes come from the docid of the URL. As a result,
* URLs with lower priority numbers will be crawled earlier. If priority
* numbers are the same, those found at lower depths will be crawled earlier.
* If depth is also equal, those found earlier (therefore, smaller docid) will
* be crawled earlier.
*/
protected DatabaseEntry getDatabaseEntryKey(WebURL url) {
byte[] keyData = new byte[6];
keyData[0] = url.getPriority();
keyData[1] = (url.getDepth() > Byte.MAX_VALUE ? Byte.MAX_VALUE : (byte) url.getDepth());
Util.putIntInByteArray(url.getDocid(), keyData, 2);
return new DatabaseEntry(keyData);
}
public void put(WebURL url) throws DatabaseException {
DatabaseEntry value = new DatabaseEntry();
webURLBinding.objectToEntry(url, value);
Transaction txn;
if (resumable) {
txn = env.beginTransaction(null, null);
} else {
txn = null;
}
urlsDB.put(txn, getDatabaseEntryKey(url), value);
if (resumable) {
if (txn != null) {
txn.commit();
}
}
}
public long getLength() {
try {
return urlsDB.count();
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public void sync() {
if (resumable) {
return;
}
if (urlsDB == null) {
return;
}
try {
urlsDB.sync();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
public void close() {
try {
urlsDB.close();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/frontier/WorkQueues.java | Java | asf20 | 5,325 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.frontier;
import org.apache.log4j.Logger;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* This class maintains the list of pages which are
* assigned to crawlers but are not yet processed.
* It is used for resuming a previous crawl.
*
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class InProcessPagesDB extends WorkQueues {
private static final Logger logger = Logger.getLogger(InProcessPagesDB.class.getName());
public InProcessPagesDB(Environment env) throws DatabaseException {
super(env, "InProcessPagesDB", true);
long docCount = getLength();
if (docCount > 0) {
logger.info("Loaded " + docCount + " URLs that have been in process in the previous crawl.");
}
}
public boolean removeURL(WebURL webUrl) {
synchronized (mutex) {
try {
DatabaseEntry key = getDatabaseEntryKey(webUrl);
Cursor cursor = null;
OperationStatus result;
DatabaseEntry value = new DatabaseEntry();
Transaction txn = env.beginTransaction(null, null);
try {
cursor = urlsDB.openCursor(txn, null);
result = cursor.getSearchKey(key, value, null);
if (result == OperationStatus.SUCCESS) {
result = cursor.delete();
if (result == OperationStatus.SUCCESS) {
return true;
}
}
} catch (DatabaseException e) {
if (txn != null) {
txn.abort();
txn = null;
}
throw e;
} finally {
if (cursor != null) {
cursor.close();
}
if (txn != null) {
txn.commit();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/frontier/InProcessPagesDB.java | Java | asf20 | 2,674 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.frontier;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class WebURLTupleBinding extends TupleBinding<WebURL> {
@Override
public WebURL entryToObject(TupleInput input) {
WebURL webURL = new WebURL();
webURL.setURL(input.readString());
webURL.setDocid(input.readInt());
webURL.setParentDocid(input.readInt());
webURL.setParentUrl(input.readString());
webURL.setDepth(input.readShort());
webURL.setPriority(input.readByte());
webURL.setAnchor(input.readString());
return webURL;
}
@Override
public void objectToEntry(WebURL url, TupleOutput output) {
output.writeString(url.getURL());
output.writeInt(url.getDocid());
output.writeInt(url.getParentDocid());
output.writeString(url.getParentUrl());
output.writeShort(url.getDepth());
output.writeByte(url.getPriority());
output.writeString(url.getAnchor());
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/frontier/WebURLTupleBinding.java | Java | asf20 | 1,890 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.frontier;
import org.apache.log4j.Logger;
import com.sleepycat.je.*;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.util.Util;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class DocIDServer extends Configurable {
protected static final Logger logger = Logger.getLogger(DocIDServer.class.getName());
protected Database docIDsDB = null;
protected final Object mutex = new Object();
protected int lastDocID;
public DocIDServer(Environment env, CrawlConfig config) throws DatabaseException {
super(config);
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
dbConfig.setTransactional(config.isResumableCrawling());
dbConfig.setDeferredWrite(!config.isResumableCrawling());
docIDsDB = env.openDatabase(null, "DocIDs", dbConfig);
if (config.isResumableCrawling()) {
int docCount = getDocCount();
if (docCount > 0) {
logger.info("Loaded " + docCount + " URLs that had been detected in previous crawl.");
lastDocID = docCount;
}
} else {
lastDocID = 0;
}
}
/**
* Returns the docid of an already seen url.
*
* @param url the URL for which the docid is returned.
* @return the docid of the url if it is seen before. Otherwise -1 is returned.
*/
public int getDocId(String url) {
synchronized (mutex) {
if (docIDsDB == null) {
return -1;
}
OperationStatus result;
DatabaseEntry value = new DatabaseEntry();
try {
DatabaseEntry key = new DatabaseEntry(url.getBytes());
result = docIDsDB.get(null, key, value, null);
if (result == OperationStatus.SUCCESS && value.getData().length > 0) {
return Util.byteArray2Int(value.getData());
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
}
public int getNewDocID(String url) {
synchronized (mutex) {
try {
// Make sure that we have not already assigned a docid for this URL
int docid = getDocId(url);
if (docid > 0) {
return docid;
}
lastDocID++;
docIDsDB.put(null, new DatabaseEntry(url.getBytes()), new DatabaseEntry(Util.int2ByteArray(lastDocID)));
return lastDocID;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
}
public void addUrlAndDocId(String url, int docId) throws Exception {
synchronized (mutex) {
if (docId <= lastDocID) {
throw new Exception("Requested doc id: " + docId + " is not larger than: " + lastDocID);
}
// Make sure that we have not already assigned a docid for this URL
int prevDocid = getDocId(url);
if (prevDocid > 0) {
if (prevDocid == docId) {
return;
}
throw new Exception("Doc id: " + prevDocid + " is already assigned to URL: " + url);
}
docIDsDB.put(null, new DatabaseEntry(url.getBytes()), new DatabaseEntry(Util.int2ByteArray(docId)));
lastDocID = docId;
}
}
public boolean isSeenBefore(String url) {
return getDocId(url) != -1;
}
public int getDocCount() {
try {
return (int) docIDsDB.count();
} catch (DatabaseException e) {
e.printStackTrace();
}
return -1;
}
public void sync() {
if (config.isResumableCrawling()) {
return;
}
if (docIDsDB == null) {
return;
}
try {
docIDsDB.sync();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
public void close() {
try {
docIDsDB.close();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/frontier/DocIDServer.java | Java | asf20 | 4,339 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.frontier;
import com.sleepycat.je.*;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.util.Util;
import java.util.HashMap;
import java.util.Map;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class Counters extends Configurable {
public class ReservedCounterNames {
public final static String SCHEDULED_PAGES = "Scheduled-Pages";
public final static String PROCESSED_PAGES = "Processed-Pages";
}
protected Database statisticsDB = null;
protected Environment env;
protected final Object mutex = new Object();
protected Map<String, Long> counterValues;
public Counters(Environment env, CrawlConfig config) throws DatabaseException {
super(config);
this.env = env;
this.counterValues = new HashMap<>();
/*
* When crawling is set to be resumable, we have to keep the statistics
* in a transactional database to make sure they are not lost if crawler
* is crashed or terminated unexpectedly.
*/
if (config.isResumableCrawling()) {
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
dbConfig.setTransactional(true);
dbConfig.setDeferredWrite(false);
statisticsDB = env.openDatabase(null, "Statistics", dbConfig);
OperationStatus result;
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry value = new DatabaseEntry();
Transaction tnx = env.beginTransaction(null, null);
Cursor cursor = statisticsDB.openCursor(tnx, null);
result = cursor.getFirst(key, value, null);
while (result == OperationStatus.SUCCESS) {
if (value.getData().length > 0) {
String name = new String(key.getData());
long counterValue = Util.byteArray2Long(value.getData());
counterValues.put(name, new Long(counterValue));
}
result = cursor.getNext(key, value, null);
}
cursor.close();
tnx.commit();
}
}
public long getValue(String name) {
synchronized (mutex) {
Long value = counterValues.get(name);
if (value == null) {
return 0;
}
return value.longValue();
}
}
public void setValue(String name, long value) {
synchronized (mutex) {
try {
counterValues.put(name, new Long(value));
if (statisticsDB != null) {
Transaction txn = env.beginTransaction(null, null);
statisticsDB.put(txn, new DatabaseEntry(name.getBytes()),
new DatabaseEntry(Util.long2ByteArray(value)));
txn.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void increment(String name) {
increment(name, 1);
}
public void increment(String name, long addition) {
synchronized (mutex) {
long prevValue = getValue(name);
setValue(name, prevValue + addition);
}
}
public void sync() {
if (config.isResumableCrawling()) {
return;
}
if (statisticsDB == null) {
return;
}
try {
statisticsDB.sync();
} catch (DatabaseException e) {
e.printStackTrace();
}
}
public void close() {
try {
if (statisticsDB != null) {
statisticsDB.close();
}
} catch (DatabaseException e) {
e.printStackTrace();
}
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/frontier/Counters.java | Java | asf20 | 3,987 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.frontier;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.frontier.Counters.ReservedCounterNames;
import edu.uci.ics.crawler4j.url.WebURL;
import org.apache.log4j.Logger;
import java.util.List;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class Frontier extends Configurable {
protected static final Logger logger = Logger.getLogger(Frontier.class.getName());
protected WorkQueues workQueues;
protected InProcessPagesDB inProcessPages;
protected final Object mutex = new Object();
protected final Object waitingList = new Object();
protected boolean isFinished = false;
protected long scheduledPages;
protected DocIDServer docIdServer;
protected Counters counters;
public Frontier(Environment env, CrawlConfig config, DocIDServer docIdServer) {
super(config);
this.counters = new Counters(env, config);
this.docIdServer = docIdServer;
try {
workQueues = new WorkQueues(env, "PendingURLsDB", config.isResumableCrawling());
if (config.isResumableCrawling()) {
scheduledPages = counters.getValue(ReservedCounterNames.SCHEDULED_PAGES);
inProcessPages = new InProcessPagesDB(env);
long numPreviouslyInProcessPages = inProcessPages.getLength();
if (numPreviouslyInProcessPages > 0) {
logger.info("Rescheduling " + numPreviouslyInProcessPages + " URLs from previous crawl.");
scheduledPages -= numPreviouslyInProcessPages;
while (true) {
List<WebURL> urls = inProcessPages.get(100);
if (urls.size() == 0) {
break;
}
scheduleAll(urls);
inProcessPages.delete(urls.size());
}
}
} else {
inProcessPages = null;
scheduledPages = 0;
}
} catch (DatabaseException e) {
logger.error("Error while initializing the Frontier: " + e.getMessage());
workQueues = null;
}
}
public void scheduleAll(List<WebURL> urls) {
int maxPagesToFetch = config.getMaxPagesToFetch();
synchronized (mutex) {
int newScheduledPage = 0;
for (WebURL url : urls) {
if (maxPagesToFetch > 0 && (scheduledPages + newScheduledPage) >= maxPagesToFetch) {
break;
}
try {
workQueues.put(url);
newScheduledPage++;
} catch (DatabaseException e) {
logger.error("Error while puting the url in the work queue.");
}
}
if (newScheduledPage > 0) {
scheduledPages += newScheduledPage;
counters.increment(Counters.ReservedCounterNames.SCHEDULED_PAGES, newScheduledPage);
}
synchronized (waitingList) {
waitingList.notifyAll();
}
}
}
public void schedule(WebURL url) {
int maxPagesToFetch = config.getMaxPagesToFetch();
synchronized (mutex) {
try {
if (maxPagesToFetch < 0 || scheduledPages < maxPagesToFetch) {
workQueues.put(url);
scheduledPages++;
counters.increment(Counters.ReservedCounterNames.SCHEDULED_PAGES);
}
} catch (DatabaseException e) {
logger.error("Error while puting the url in the work queue.");
}
}
}
public void getNextURLs(int max, List<WebURL> result) {
while (true) {
synchronized (mutex) {
if (isFinished) {
return;
}
try {
List<WebURL> curResults = workQueues.get(max);
workQueues.delete(curResults.size());
if (inProcessPages != null) {
for (WebURL curPage : curResults) {
inProcessPages.put(curPage);
}
}
result.addAll(curResults);
} catch (DatabaseException e) {
logger.error("Error while getting next urls: " + e.getMessage());
e.printStackTrace();
}
if (result.size() > 0) {
return;
}
}
try {
synchronized (waitingList) {
waitingList.wait();
}
} catch (InterruptedException ignored) {
// Do nothing
}
if (isFinished) {
return;
}
}
}
public void setProcessed(WebURL webURL) {
counters.increment(ReservedCounterNames.PROCESSED_PAGES);
if (inProcessPages != null) {
if (!inProcessPages.removeURL(webURL)) {
logger.warn("Could not remove: " + webURL.getURL() + " from list of processed pages.");
}
}
}
public long getQueueLength() {
return workQueues.getLength();
}
public long getNumberOfAssignedPages() {
return inProcessPages.getLength();
}
public long getNumberOfProcessedPages() {
return counters.getValue(ReservedCounterNames.PROCESSED_PAGES);
}
public void sync() {
workQueues.sync();
docIdServer.sync();
counters.sync();
}
public boolean isFinished() {
return isFinished;
}
public void close() {
sync();
workQueues.close();
counters.close();
}
public void finish() {
isFinished = true;
synchronized (waitingList) {
waitingList.notifyAll();
}
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/frontier/Frontier.java | Java | asf20 | 5,677 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.parser;
public class BinaryParseData implements ParseData {
private static BinaryParseData instance = new BinaryParseData();
public static BinaryParseData getInstance() {
return instance;
}
@Override
public String toString() {
return "[Binary parse data can not be dumped as string]";
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/parser/BinaryParseData.java | Java | asf20 | 1,139 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.parser;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.List;
public class HtmlParseData implements ParseData {
private String html;
private String text;
private String title;
private List<WebURL> outgoingUrls;
public String getHtml() {
return html;
}
public void setHtml(String html) {
this.html = html;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<WebURL> getOutgoingUrls() {
return outgoingUrls;
}
public void setOutgoingUrls(List<WebURL> outgoingUrls) {
this.outgoingUrls = outgoingUrls;
}
@Override
public String toString() {
return text;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/parser/HtmlParseData.java | Java | asf20 | 1,616 |
package edu.uci.ics.crawler4j.parser;
public class ExtractedUrlAnchorPair {
private String href;
private String anchor;
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getAnchor() {
return anchor;
}
public void setAnchor(String anchor) {
this.anchor = anchor;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/parser/ExtractedUrlAnchorPair.java | Java | asf20 | 351 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.parser;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.tika.metadata.DublinCore;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.html.HtmlParser;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.url.URLCanonicalizer;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.Util;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class Parser extends Configurable {
protected static final Logger logger = Logger.getLogger(Parser.class.getName());
private HtmlParser htmlParser;
private ParseContext parseContext;
public Parser(CrawlConfig config) {
super(config);
htmlParser = new HtmlParser();
parseContext = new ParseContext();
}
public boolean parse(Page page, String contextURL) {
if (Util.hasBinaryContent(page.getContentType())) {
if (!config.isIncludeBinaryContentInCrawling()) {
return false;
}
page.setParseData(BinaryParseData.getInstance());
return true;
} else if (Util.hasPlainTextContent(page.getContentType())) {
try {
TextParseData parseData = new TextParseData();
if (page.getContentCharset() == null) {
parseData.setTextContent(new String(page.getContentData()));
} else {
parseData.setTextContent(new String(page.getContentData(), page.getContentCharset()));
}
page.setParseData(parseData);
return true;
} catch (Exception e) {
logger.error(e.getMessage() + ", while parsing: " + page.getWebURL().getURL());
}
return false;
}
Metadata metadata = new Metadata();
HtmlContentHandler contentHandler = new HtmlContentHandler();
InputStream inputStream = null;
try {
inputStream = new ByteArrayInputStream(page.getContentData());
htmlParser.parse(inputStream, contentHandler, metadata, parseContext);
} catch (Exception e) {
logger.error(e.getMessage() + ", while parsing: " + page.getWebURL().getURL());
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
logger.error(e.getMessage() + ", while parsing: " + page.getWebURL().getURL());
}
}
if (page.getContentCharset() == null) {
page.setContentCharset(metadata.get("Content-Encoding"));
}
HtmlParseData parseData = new HtmlParseData();
parseData.setText(contentHandler.getBodyText().trim());
parseData.setTitle(metadata.get(DublinCore.TITLE));
List<WebURL> outgoingUrls = new ArrayList<>();
String baseURL = contentHandler.getBaseUrl();
if (baseURL != null) {
contextURL = baseURL;
}
int urlCount = 0;
for (ExtractedUrlAnchorPair urlAnchorPair : contentHandler.getOutgoingUrls()) {
String href = urlAnchorPair.getHref();
href = href.trim();
if (href.length() == 0) {
continue;
}
String hrefWithoutProtocol = href.toLowerCase();
if (href.startsWith("http://")) {
hrefWithoutProtocol = href.substring(7);
}
if (!hrefWithoutProtocol.contains("javascript:") && !hrefWithoutProtocol.contains("mailto:")
&& !hrefWithoutProtocol.contains("@")) {
String url = URLCanonicalizer.getCanonicalURL(href, contextURL);
if (url != null) {
WebURL webURL = new WebURL();
webURL.setURL(url);
webURL.setAnchor(urlAnchorPair.getAnchor());
outgoingUrls.add(webURL);
urlCount++;
if (urlCount > config.getMaxOutgoingLinksToFollow()) {
break;
}
}
}
}
parseData.setOutgoingUrls(outgoingUrls);
try {
if (page.getContentCharset() == null) {
parseData.setHtml(new String(page.getContentData()));
} else {
parseData.setHtml(new String(page.getContentData(), page.getContentCharset()));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return false;
}
page.setParseData(parseData);
return true;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/parser/Parser.java | Java | asf20 | 4,966 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.parser;
public class TextParseData implements ParseData {
private String textContent;
public String getTextContent() {
return textContent;
}
public void setTextContent(String textContent) {
this.textContent = textContent;
}
@Override
public String toString() {
return textContent;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/parser/TextParseData.java | Java | asf20 | 1,141 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class HtmlContentHandler extends DefaultHandler {
private final int MAX_ANCHOR_LENGTH = 100;
private enum Element {
A, AREA, LINK, IFRAME, FRAME, EMBED, IMG, BASE, META, BODY
}
private static class HtmlFactory {
private static Map<String, Element> name2Element;
static {
name2Element = new HashMap<>();
for (Element element : Element.values()) {
name2Element.put(element.toString().toLowerCase(), element);
}
}
public static Element getElement(String name) {
return name2Element.get(name);
}
}
private String base;
private String metaRefresh;
private String metaLocation;
private boolean isWithinBodyElement;
private StringBuilder bodyText;
private List<ExtractedUrlAnchorPair> outgoingUrls;
private ExtractedUrlAnchorPair curUrl = null;
private boolean anchorFlag = false;
private StringBuilder anchorText = new StringBuilder();
public HtmlContentHandler() {
isWithinBodyElement = false;
bodyText = new StringBuilder();
outgoingUrls = new ArrayList<>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
Element element = HtmlFactory.getElement(localName);
if (element == Element.A || element == Element.AREA || element == Element.LINK) {
String href = attributes.getValue("href");
if (href != null) {
anchorFlag = true;
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(href);
outgoingUrls.add(curUrl);
}
return;
}
if (element == Element.IMG) {
String imgSrc = attributes.getValue("src");
if (imgSrc != null) {
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(imgSrc);
outgoingUrls.add(curUrl);
}
return;
}
if (element == Element.IFRAME || element == Element.FRAME || element == Element.EMBED) {
String src = attributes.getValue("src");
if (src != null) {
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(src);
outgoingUrls.add(curUrl);
}
return;
}
if (element == Element.BASE) {
if (base != null) { // We only consider the first occurrence of the
// Base element.
String href = attributes.getValue("href");
if (href != null) {
base = href;
}
}
return;
}
if (element == Element.META) {
String equiv = attributes.getValue("http-equiv");
String content = attributes.getValue("content");
if (equiv != null && content != null) {
equiv = equiv.toLowerCase();
// http-equiv="refresh" content="0;URL=http://foo.bar/..."
if (equiv.equals("refresh") && (metaRefresh == null)) {
int pos = content.toLowerCase().indexOf("url=");
if (pos != -1) {
metaRefresh = content.substring(pos + 4);
}
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(metaRefresh);
outgoingUrls.add(curUrl);
}
// http-equiv="location" content="http://foo.bar/..."
if (equiv.equals("location") && (metaLocation == null)) {
metaLocation = content;
curUrl = new ExtractedUrlAnchorPair();
curUrl.setHref(metaRefresh);
outgoingUrls.add(curUrl);
}
}
return;
}
if (element == Element.BODY) {
isWithinBodyElement = true;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
Element element = HtmlFactory.getElement(localName);
if (element == Element.A || element == Element.AREA || element == Element.LINK) {
anchorFlag = false;
if (curUrl != null) {
String anchor = anchorText.toString().replaceAll("\n", " ").replaceAll("\t", " ").trim();
if (!anchor.isEmpty()) {
if (anchor.length() > MAX_ANCHOR_LENGTH) {
anchor = anchor.substring(0, MAX_ANCHOR_LENGTH) + "...";
}
curUrl.setAnchor(anchor);
}
anchorText.delete(0, anchorText.length());
}
curUrl = null;
}
if (element == Element.BODY) {
isWithinBodyElement = false;
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
if (isWithinBodyElement) {
bodyText.append(ch, start, length);
if (anchorFlag) {
anchorText.append(new String(ch, start, length));
}
}
}
public String getBodyText() {
return bodyText.toString();
}
public List<ExtractedUrlAnchorPair> getOutgoingUrls() {
return outgoingUrls;
}
public String getBaseUrl() {
return base;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/parser/HtmlContentHandler.java | Java | asf20 | 5,404 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.parser;
public interface ParseData {
@Override
public String toString();
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/parser/ParseData.java | Java | asf20 | 918 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.fetcher;
import java.util.concurrent.TimeUnit;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
public class IdleConnectionMonitorThread extends Thread {
private final PoolingClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionMonitorThread(PoolingClientConnectionManager connMgr) {
super("Connection Manager");
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 30 sec
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/fetcher/IdleConnectionMonitorThread.java | Java | asf20 | 1,971 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"; you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.fetcher;
import org.apache.http.HttpStatus;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class CustomFetchStatus {
public static final int PageTooBig = 1001;
public static final int FatalTransportError = 1005;
public static final int UnknownError = 1006;
public static String getStatusDescription(int code) {
switch (code) {
case HttpStatus.SC_OK:
return "OK";
case HttpStatus.SC_CREATED:
return "Created";
case HttpStatus.SC_ACCEPTED:
return "Accepted";
case HttpStatus.SC_NO_CONTENT:
return "No Content";
case HttpStatus.SC_MOVED_PERMANENTLY:
return "Moved Permanently";
case HttpStatus.SC_MOVED_TEMPORARILY:
return "Moved Temporarily";
case HttpStatus.SC_NOT_MODIFIED:
return "Not Modified";
case HttpStatus.SC_BAD_REQUEST:
return "Bad Request";
case HttpStatus.SC_UNAUTHORIZED:
return "Unauthorized";
case HttpStatus.SC_FORBIDDEN:
return "Forbidden";
case HttpStatus.SC_NOT_FOUND:
return "Not Found";
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
return "Internal Server Error";
case HttpStatus.SC_NOT_IMPLEMENTED:
return "Not Implemented";
case HttpStatus.SC_BAD_GATEWAY:
return "Bad Gateway";
case HttpStatus.SC_SERVICE_UNAVAILABLE:
return "Service Unavailable";
case HttpStatus.SC_CONTINUE:
return "Continue";
case HttpStatus.SC_TEMPORARY_REDIRECT:
return "Temporary Redirect";
case HttpStatus.SC_METHOD_NOT_ALLOWED:
return "Method Not Allowed";
case HttpStatus.SC_CONFLICT:
return "Conflict";
case HttpStatus.SC_PRECONDITION_FAILED:
return "Precondition Failed";
case HttpStatus.SC_REQUEST_TOO_LONG:
return "Request Too Long";
case HttpStatus.SC_REQUEST_URI_TOO_LONG:
return "Request-URI Too Long";
case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
return "Unsupported Media Type";
case HttpStatus.SC_MULTIPLE_CHOICES:
return "Multiple Choices";
case HttpStatus.SC_SEE_OTHER:
return "See Other";
case HttpStatus.SC_USE_PROXY:
return "Use Proxy";
case HttpStatus.SC_PAYMENT_REQUIRED:
return "Payment Required";
case HttpStatus.SC_NOT_ACCEPTABLE:
return "Not Acceptable";
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
return "Proxy Authentication Required";
case HttpStatus.SC_REQUEST_TIMEOUT:
return "Request Timeout";
case PageTooBig:
return "Page size was too big";
case FatalTransportError:
return "Fatal transport error";
case UnknownError:
return "Unknown error";
default:
return "(" + code + ")";
}
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/fetcher/CustomFetchStatus.java | Java | asf20 | 3,354 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.fetcher;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParamBean;
import org.apache.http.protocol.HttpContext;
import org.apache.log4j.Logger;
import edu.uci.ics.crawler4j.crawler.Configurable;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.url.URLCanonicalizer;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class PageFetcher extends Configurable {
protected static final Logger logger = Logger.getLogger(PageFetcher.class);
protected PoolingClientConnectionManager connectionManager;
protected DefaultHttpClient httpClient;
protected final Object mutex = new Object();
protected long lastFetchTime = 0;
protected IdleConnectionMonitorThread connectionMonitorThread = null;
public PageFetcher(CrawlConfig config) {
super(config);
HttpParams params = new BasicHttpParams();
HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
paramsBean.setVersion(HttpVersion.HTTP_1_1);
paramsBean.setContentCharset("UTF-8");
paramsBean.setUseExpectContinue(false);
params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());
params.setBooleanParameter("http.protocol.handle-redirects", false);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
if (config.isIncludeHttpsPages()) {
schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
}
connectionManager = new PoolingClientConnectionManager(schemeRegistry);
connectionManager.setMaxTotal(config.getMaxTotalConnections());
connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
httpClient = new DefaultHttpClient(connectionManager, params);
if (config.getProxyHost() != null) {
if (config.getProxyUsername() != null) {
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(config.getProxyHost(), config.getProxyPort()),
new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
}
HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
@Override
public void process(final HttpResponse response, final HttpContext context) throws HttpException,
IOException {
HttpEntity entity = response.getEntity();
Header contentEncoding = entity.getContentEncoding();
if (contentEncoding != null) {
HeaderElement[] codecs = contentEncoding.getElements();
for (HeaderElement codec : codecs) {
if (codec.getName().equalsIgnoreCase("gzip")) {
response.setEntity(new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
if (connectionMonitorThread == null) {
connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
}
connectionMonitorThread.start();
}
public PageFetchResult fetchHeader(WebURL webUrl) {
PageFetchResult fetchResult = new PageFetchResult();
String toFetchURL = webUrl.getURL();
HttpGet get = null;
try {
get = new HttpGet(toFetchURL);
synchronized (mutex) {
long now = (new Date()).getTime();
if (now - lastFetchTime < config.getPolitenessDelay()) {
Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime));
}
lastFetchTime = (new Date()).getTime();
}
get.addHeader("Accept-Encoding", "gzip");
HttpResponse response = httpClient.execute(get);
fetchResult.setEntity(response.getEntity());
fetchResult.setResponseHeaders(response.getAllHeaders());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
if (statusCode != HttpStatus.SC_NOT_FOUND) {
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
Header header = response.getFirstHeader("Location");
if (header != null) {
String movedToUrl = header.getValue();
movedToUrl = URLCanonicalizer.getCanonicalURL(movedToUrl, toFetchURL);
fetchResult.setMovedToUrl(movedToUrl);
}
fetchResult.setStatusCode(statusCode);
return fetchResult;
}
logger.info("Failed: " + response.getStatusLine().toString() + ", while fetching " + toFetchURL);
}
fetchResult.setStatusCode(response.getStatusLine().getStatusCode());
return fetchResult;
}
fetchResult.setFetchedUrl(toFetchURL);
String uri = get.getURI().toString();
if (!uri.equals(toFetchURL)) {
if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL)) {
fetchResult.setFetchedUrl(uri);
}
}
if (fetchResult.getEntity() != null) {
long size = fetchResult.getEntity().getContentLength();
if (size == -1) {
Header length = response.getLastHeader("Content-Length");
if (length == null) {
length = response.getLastHeader("Content-length");
}
if (length != null) {
size = Integer.parseInt(length.getValue());
} else {
size = -1;
}
}
if (size > config.getMaxDownloadSize()) {
fetchResult.setStatusCode(CustomFetchStatus.PageTooBig);
get.abort();
return fetchResult;
}
fetchResult.setStatusCode(HttpStatus.SC_OK);
return fetchResult;
}
get.abort();
} catch (IOException e) {
logger.error("Fatal transport error: " + e.getMessage() + " while fetching " + toFetchURL
+ " (link found in doc #" + webUrl.getParentDocid() + ")");
fetchResult.setStatusCode(CustomFetchStatus.FatalTransportError);
return fetchResult;
} catch (IllegalStateException e) {
// ignoring exceptions that occur because of not registering https
// and other schemes
} catch (Exception e) {
if (e.getMessage() == null) {
logger.error("Error while fetching " + webUrl.getURL());
} else {
logger.error(e.getMessage() + " while fetching " + webUrl.getURL());
}
} finally {
try {
if (fetchResult.getEntity() == null && get != null) {
get.abort();
}
} catch (Exception e) {
e.printStackTrace();
}
}
fetchResult.setStatusCode(CustomFetchStatus.UnknownError);
return fetchResult;
}
public synchronized void shutDown() {
if (connectionMonitorThread != null) {
connectionManager.shutdown();
connectionMonitorThread.shutdown();
}
}
public HttpClient getHttpClient() {
return httpClient;
}
private static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent() throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/fetcher/PageFetcher.java | Java | asf20 | 9,777 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.fetcher;
import java.io.EOFException;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import edu.uci.ics.crawler4j.crawler.Page;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class PageFetchResult {
protected static final Logger logger = Logger.getLogger(PageFetchResult.class);
protected int statusCode;
protected HttpEntity entity = null;
protected Header[] responseHeaders = null;
protected String fetchedUrl = null;
protected String movedToUrl = null;
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public HttpEntity getEntity() {
return entity;
}
public void setEntity(HttpEntity entity) {
this.entity = entity;
}
public Header[] getResponseHeaders() {
return responseHeaders;
}
public void setResponseHeaders(Header[] responseHeaders) {
this.responseHeaders = responseHeaders;
}
public String getFetchedUrl() {
return fetchedUrl;
}
public void setFetchedUrl(String fetchedUrl) {
this.fetchedUrl = fetchedUrl;
}
public boolean fetchContent(Page page) {
try {
page.load(entity);
page.setFetchResponseHeaders(responseHeaders);
return true;
} catch (Exception e) {
logger.info("Exception while fetching content for: " + page.getWebURL().getURL() + " [" + e.getMessage()
+ "]");
}
return false;
}
public void discardContentIfNotConsumed() {
try {
if (entity != null) {
EntityUtils.consume(entity);
}
} catch (EOFException e) {
// We can ignore this exception. It can happen on compressed streams
// which are not repeatable
} catch (IOException e) {
// We can ignore this exception. It can happen if the stream is
// closed.
} catch (Exception e) {
e.printStackTrace();
}
}
public String getMovedToUrl() {
return movedToUrl;
}
public void setMovedToUrl(String movedToUrl) {
this.movedToUrl = movedToUrl;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/fetcher/PageFetchResult.java | Java | asf20 | 2,899 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.url;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* See http://en.wikipedia.org/wiki/URL_normalization for a reference Note: some
* parts of the code are adapted from: http://stackoverflow.com/a/4057470/405418
*
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class URLCanonicalizer {
public static String getCanonicalURL(String url) {
return getCanonicalURL(url, null);
}
public static String getCanonicalURL(String href, String context) {
try {
URL canonicalURL = new URL(UrlResolver.resolveUrl(context == null ? "" : context, href));
String host = canonicalURL.getHost().toLowerCase();
if (host == "") {
// This is an invalid Url.
return null;
}
String path = canonicalURL.getPath();
/*
* Normalize: no empty segments (i.e., "//"), no segments equal to
* ".", and no segments equal to ".." that are preceded by a segment
* not equal to "..".
*/
path = new URI(path).normalize().toString();
/*
* Convert '//' -> '/'
*/
int idx = path.indexOf("//");
while (idx >= 0) {
path = path.replace("//", "/");
idx = path.indexOf("//");
}
/*
* Drop starting '/../'
*/
while (path.startsWith("/../")) {
path = path.substring(3);
}
/*
* Trim
*/
path = path.trim();
final SortedMap<String, String> params = createParameterMap(canonicalURL.getQuery());
final String queryString;
if (params != null && params.size() > 0) {
String canonicalParams = canonicalize(params);
queryString = (canonicalParams.isEmpty() ? "" : "?" + canonicalParams);
} else {
queryString = "";
}
/*
* Add starting slash if needed
*/
if (path.length() == 0) {
path = "/" + path;
}
/*
* Drop default port: example.com:80 -> example.com
*/
int port = canonicalURL.getPort();
if (port == canonicalURL.getDefaultPort()) {
port = -1;
}
String protocol = canonicalURL.getProtocol().toLowerCase();
String pathAndQueryString = normalizePath(path) + queryString;
URL result = new URL(protocol, host, port, pathAndQueryString);
return result.toExternalForm();
} catch (MalformedURLException ex) {
return null;
} catch (URISyntaxException ex) {
return null;
}
}
/**
* Takes a query string, separates the constituent name-value pairs, and
* stores them in a SortedMap ordered by lexicographical order.
*
* @return Null if there is no query string.
*/
private static SortedMap<String, String> createParameterMap(final String queryString) {
if (queryString == null || queryString.isEmpty()) {
return null;
}
final String[] pairs = queryString.split("&");
final Map<String, String> params = new HashMap<>(pairs.length);
for (final String pair : pairs) {
if (pair.length() == 0) {
continue;
}
String[] tokens = pair.split("=", 2);
switch (tokens.length) {
case 1:
if (pair.charAt(0) == '=') {
params.put("", tokens[0]);
} else {
params.put(tokens[0], "");
}
break;
case 2:
params.put(tokens[0], tokens[1]);
break;
}
}
return new TreeMap<>(params);
}
/**
* Canonicalize the query string.
*
* @param sortedParamMap
* Parameter name-value pairs in lexicographical order.
* @return Canonical form of query string.
*/
private static String canonicalize(final SortedMap<String, String> sortedParamMap) {
if (sortedParamMap == null || sortedParamMap.isEmpty()) {
return "";
}
final StringBuffer sb = new StringBuffer(100);
for (Map.Entry<String, String> pair : sortedParamMap.entrySet()) {
final String key = pair.getKey().toLowerCase();
if (key.equals("jsessionid") || key.equals("phpsessid") || key.equals("aspsessionid")) {
continue;
}
if (sb.length() > 0) {
sb.append('&');
}
sb.append(percentEncodeRfc3986(pair.getKey()));
if (!pair.getValue().isEmpty()) {
sb.append('=');
sb.append(percentEncodeRfc3986(pair.getValue()));
}
}
return sb.toString();
}
/**
* Percent-encode values according the RFC 3986. The built-in Java
* URLEncoder does not encode according to the RFC, so we make the extra
* replacements.
*
* @param string
* Decoded string.
* @return Encoded string per RFC 3986.
*/
private static String percentEncodeRfc3986(String string) {
try {
string = string.replace("+", "%2B");
string = URLDecoder.decode(string, "UTF-8");
string = URLEncoder.encode(string, "UTF-8");
return string.replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
} catch (Exception e) {
return string;
}
}
private static String normalizePath(final String path) {
return path.replace("%7E", "~").replace(" ", "%20");
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/url/URLCanonicalizer.java | Java | asf20 | 5,820 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.url;
import java.io.Serializable;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
@Entity
public class WebURL implements Serializable {
private static final long serialVersionUID = 1L;
@PrimaryKey
private String url;
private int docid;
private int parentDocid;
private String parentUrl;
private short depth;
private String domain;
private String subDomain;
private String path;
private String anchor;
private byte priority;
/**
* Returns the unique document id assigned to this Url.
*/
public int getDocid() {
return docid;
}
public void setDocid(int docid) {
this.docid = docid;
}
@Override
public int hashCode() {
return url.hashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WebURL otherUrl = (WebURL) o;
return url != null && url.equals(otherUrl.getURL());
}
@Override
public String toString() {
return url;
}
/**
* Returns the Url string
*/
public String getURL() {
return url;
}
public void setURL(String url) {
this.url = url;
int domainStartIdx = url.indexOf("//") + 2;
int domainEndIdx = url.indexOf('/', domainStartIdx);
domain = url.substring(domainStartIdx, domainEndIdx);
subDomain = "";
String[] parts = domain.split("\\.");
if (parts.length > 2) {
domain = parts[parts.length - 2] + "." + parts[parts.length - 1];
int limit = 2;
if (TLDList.getInstance().contains(domain)) {
domain = parts[parts.length - 3] + "." + domain;
limit = 3;
}
for (int i = 0; i < parts.length - limit; i++) {
if (subDomain.length() > 0) {
subDomain += ".";
}
subDomain += parts[i];
}
}
path = url.substring(domainEndIdx);
int pathEndIdx = path.indexOf('?');
if (pathEndIdx >= 0) {
path = path.substring(0, pathEndIdx);
}
}
/**
* Returns the unique document id of the parent page. The parent page is the
* page in which the Url of this page is first observed.
*/
public int getParentDocid() {
return parentDocid;
}
public void setParentDocid(int parentDocid) {
this.parentDocid = parentDocid;
}
/**
* Returns the url of the parent page. The parent page is the page in which
* the Url of this page is first observed.
*/
public String getParentUrl() {
return parentUrl;
}
public void setParentUrl(String parentUrl) {
this.parentUrl = parentUrl;
}
/**
* Returns the crawl depth at which this Url is first observed. Seed Urls
* are at depth 0. Urls that are extracted from seed Urls are at depth 1,
* etc.
*/
public short getDepth() {
return depth;
}
public void setDepth(short depth) {
this.depth = depth;
}
/**
* Returns the domain of this Url. For 'http://www.example.com/sample.htm',
* domain will be 'example.com'
*/
public String getDomain() {
return domain;
}
public String getSubDomain() {
return subDomain;
}
/**
* Returns the path of this Url. For 'http://www.example.com/sample.htm',
* domain will be 'sample.htm'
*/
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
/**
* Returns the anchor string. For example, in <a href="example.com">A sample anchor</a>
* the anchor string is 'A sample anchor'
*/
public String getAnchor() {
return anchor;
}
public void setAnchor(String anchor) {
this.anchor = anchor;
}
/**
* Returns the priority for crawling this URL.
* A lower number results in higher priority.
*/
public byte getPriority() {
return priority;
}
public void setPriority(byte priority) {
this.priority = priority;
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/url/WebURL.java | Java | asf20 | 4,593 |
/**
* This class is adopted from Htmlunit with the following copyright:
*
* Copyright (c) 2002-2012 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.crawler4j.url;
public final class UrlResolver {
/**
* Resolves a given relative URL against a base URL. See
* <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>
* Section 4 for more details.
*
* @param baseUrl The base URL in which to resolve the specification.
* @param relativeUrl The relative URL to resolve against the base URL.
* @return the resolved specification.
*/
public static String resolveUrl(final String baseUrl, final String relativeUrl) {
if (baseUrl == null) {
throw new IllegalArgumentException("Base URL must not be null");
}
if (relativeUrl == null) {
throw new IllegalArgumentException("Relative URL must not be null");
}
final Url url = resolveUrl(parseUrl(baseUrl.trim()), relativeUrl.trim());
return url.toString();
}
/**
* Returns the index within the specified string of the first occurrence of
* the specified search character.
*
* @param s the string to search
* @param searchChar the character to search for
* @param beginIndex the index at which to start the search
* @param endIndex the index at which to stop the search
* @return the index of the first occurrence of the character in the string or <tt>-1</tt>
*/
private static int indexOf(final String s, final char searchChar, final int beginIndex, final int endIndex) {
for (int i = beginIndex; i < endIndex; i++) {
if (s.charAt(i) == searchChar) {
return i;
}
}
return -1;
}
/**
* Parses a given specification using the algorithm depicted in
* <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>:
*
* Section 2.4: Parsing a URL
*
* An accepted method for parsing URLs is useful to clarify the
* generic-RL syntax of Section 2.2 and to describe the algorithm for
* resolving relative URLs presented in Section 4. This section
* describes the parsing rules for breaking down a URL (relative or
* absolute) into the component parts described in Section 2.1. The
* rules assume that the URL has already been separated from any
* surrounding text and copied to a "parse string". The rules are
* listed in the order in which they would be applied by the parser.
*
* @param spec The specification to parse.
* @return the parsed specification.
*/
private static Url parseUrl(final String spec) {
final Url url = new Url();
int startIndex = 0;
int endIndex = spec.length();
// Section 2.4.1: Parsing the Fragment Identifier
//
// If the parse string contains a crosshatch "#" character, then the
// substring after the first (left-most) crosshatch "#" and up to the
// end of the parse string is the <fragment> identifier. If the
// crosshatch is the last character, or no crosshatch is present, then
// the fragment identifier is empty. The matched substring, including
// the crosshatch character, is removed from the parse string before
// continuing.
//
// Note that the fragment identifier is not considered part of the URL.
// However, since it is often attached to the URL, parsers must be able
// to recognize and set aside fragment identifiers as part of the
// process.
final int crosshatchIndex = indexOf(spec, '#', startIndex, endIndex);
if (crosshatchIndex >= 0) {
url.fragment_ = spec.substring(crosshatchIndex + 1, endIndex);
endIndex = crosshatchIndex;
}
// Section 2.4.2: Parsing the Scheme
//
// If the parse string contains a colon ":" after the first character
// and before any characters not allowed as part of a scheme name (i.e.,
// any not an alphanumeric, plus "+", period ".", or hyphen "-"), the
// <scheme> of the URL is the substring of characters up to but not
// including the first colon. These characters and the colon are then
// removed from the parse string before continuing.
final int colonIndex = indexOf(spec, ':', startIndex, endIndex);
if (colonIndex > 0) {
final String scheme = spec.substring(startIndex, colonIndex);
if (isValidScheme(scheme)) {
url.scheme_ = scheme;
startIndex = colonIndex + 1;
}
}
// Section 2.4.3: Parsing the Network Location/Login
//
// If the parse string begins with a double-slash "//", then the
// substring of characters after the double-slash and up to, but not
// including, the next slash "/" character is the network location/login
// (<net_loc>) of the URL. If no trailing slash "/" is present, the
// entire remaining parse string is assigned to <net_loc>. The double-
// slash and <net_loc> are removed from the parse string before
// continuing.
//
// Note: We also accept a question mark "?" or a semicolon ";" character as
// delimiters for the network location/login (<net_loc>) of the URL.
final int locationStartIndex;
int locationEndIndex;
if (spec.startsWith("//", startIndex)) {
locationStartIndex = startIndex + 2;
locationEndIndex = indexOf(spec, '/', locationStartIndex, endIndex);
if (locationEndIndex >= 0) {
startIndex = locationEndIndex;
}
}
else {
locationStartIndex = -1;
locationEndIndex = -1;
}
// Section 2.4.4: Parsing the Query Information
//
// If the parse string contains a question mark "?" character, then the
// substring after the first (left-most) question mark "?" and up to the
// end of the parse string is the <query> information. If the question
// mark is the last character, or no question mark is present, then the
// query information is empty. The matched substring, including the
// question mark character, is removed from the parse string before
// continuing.
final int questionMarkIndex = indexOf(spec, '?', startIndex, endIndex);
if (questionMarkIndex >= 0) {
if ((locationStartIndex >= 0) && (locationEndIndex < 0)) {
// The substring of characters after the double-slash and up to, but not
// including, the question mark "?" character is the network location/login
// (<net_loc>) of the URL.
locationEndIndex = questionMarkIndex;
startIndex = questionMarkIndex;
}
url.query_ = spec.substring(questionMarkIndex + 1, endIndex);
endIndex = questionMarkIndex;
}
// Section 2.4.5: Parsing the Parameters
//
// If the parse string contains a semicolon ";" character, then the
// substring after the first (left-most) semicolon ";" and up to the end
// of the parse string is the parameters (<params>). If the semicolon
// is the last character, or no semicolon is present, then <params> is
// empty. The matched substring, including the semicolon character, is
// removed from the parse string before continuing.
final int semicolonIndex = indexOf(spec, ';', startIndex, endIndex);
if (semicolonIndex >= 0) {
if ((locationStartIndex >= 0) && (locationEndIndex < 0)) {
// The substring of characters after the double-slash and up to, but not
// including, the semicolon ";" character is the network location/login
// (<net_loc>) of the URL.
locationEndIndex = semicolonIndex;
startIndex = semicolonIndex;
}
url.parameters_ = spec.substring(semicolonIndex + 1, endIndex);
endIndex = semicolonIndex;
}
// Section 2.4.6: Parsing the Path
//
// After the above steps, all that is left of the parse string is the
// URL <path> and the slash "/" that may precede it. Even though the
// initial slash is not part of the URL path, the parser must remember
// whether or not it was present so that later processes can
// differentiate between relative and absolute paths. Often this is
// done by simply storing the preceding slash along with the path.
if ((locationStartIndex >= 0) && (locationEndIndex < 0)) {
// The entire remaining parse string is assigned to the network
// location/login (<net_loc>) of the URL.
locationEndIndex = endIndex;
}
else if (startIndex < endIndex) {
url.path_ = spec.substring(startIndex, endIndex);
}
// Set the network location/login (<net_loc>) of the URL.
if ((locationStartIndex >= 0) && (locationEndIndex >= 0)) {
url.location_ = spec.substring(locationStartIndex, locationEndIndex);
}
return url;
}
/*
* Returns true if specified string is a valid scheme name.
*/
private static boolean isValidScheme(final String scheme) {
final int length = scheme.length();
if (length < 1) {
return false;
}
char c = scheme.charAt(0);
if (!Character.isLetter(c)) {
return false;
}
for (int i = 1; i < length; i++) {
c = scheme.charAt(i);
if (!Character.isLetterOrDigit(c) && c != '.' && c != '+' && c != '-') {
return false;
}
}
return true;
}
/**
* Resolves a given relative URL against a base URL using the algorithm
* depicted in <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>:
*
* Section 4: Resolving Relative URLs
*
* This section describes an example algorithm for resolving URLs within
* a context in which the URLs may be relative, such that the result is
* always a URL in absolute form. Although this algorithm cannot
* guarantee that the resulting URL will equal that intended by the
* original author, it does guarantee that any valid URL (relative or
* absolute) can be consistently transformed to an absolute form given a
* valid base URL.
*
* @param baseUrl The base URL in which to resolve the specification.
* @param relativeUrl The relative URL to resolve against the base URL.
* @return the resolved specification.
*/
private static Url resolveUrl(final Url baseUrl, final String relativeUrl) {
final Url url = parseUrl(relativeUrl);
// Step 1: The base URL is established according to the rules of
// Section 3. If the base URL is the empty string (unknown),
// the embedded URL is interpreted as an absolute URL and
// we are done.
if (baseUrl == null) {
return url;
}
// Step 2: Both the base and embedded URLs are parsed into their
// component parts as described in Section 2.4.
// a) If the embedded URL is entirely empty, it inherits the
// entire base URL (i.e., is set equal to the base URL)
// and we are done.
if (relativeUrl.length() == 0) {
return new Url(baseUrl);
}
// b) If the embedded URL starts with a scheme name, it is
// interpreted as an absolute URL and we are done.
if (url.scheme_ != null) {
return url;
}
// c) Otherwise, the embedded URL inherits the scheme of
// the base URL.
url.scheme_ = baseUrl.scheme_;
// Step 3: If the embedded URL's <net_loc> is non-empty, we skip to
// Step 7. Otherwise, the embedded URL inherits the <net_loc>
// (if any) of the base URL.
if (url.location_ != null) {
return url;
}
url.location_ = baseUrl.location_;
// Step 4: If the embedded URL path is preceded by a slash "/", the
// path is not relative and we skip to Step 7.
if ((url.path_ != null) && ((url.path_.length() > 0) && ('/' == url.path_.charAt(0)))) {
url.path_ = removeLeadingSlashPoints(url.path_);
return url;
}
// Step 5: If the embedded URL path is empty (and not preceded by a
// slash), then the embedded URL inherits the base URL path,
// and
if (url.path_ == null) {
url.path_ = baseUrl.path_;
// a) if the embedded URL's <params> is non-empty, we skip to
// step 7; otherwise, it inherits the <params> of the base
// URL (if any) and
if (url.parameters_ != null) {
return url;
}
url.parameters_ = baseUrl.parameters_;
// b) if the embedded URL's <query> is non-empty, we skip to
// step 7; otherwise, it inherits the <query> of the base
// URL (if any) and we skip to step 7.
if (url.query_ != null) {
return url;
}
url.query_ = baseUrl.query_;
return url;
}
// Step 6: The last segment of the base URL's path (anything
// following the rightmost slash "/", or the entire path if no
// slash is present) is removed and the embedded URL's path is
// appended in its place. The following operations are
// then applied, in order, to the new path:
final String basePath = baseUrl.path_;
String path = "";
if (basePath != null) {
final int lastSlashIndex = basePath.lastIndexOf('/');
if (lastSlashIndex >= 0) {
path = basePath.substring(0, lastSlashIndex + 1);
}
}
else {
path = "/";
}
path = path.concat(url.path_);
// a) All occurrences of "./", where "." is a complete path
// segment, are removed.
int pathSegmentIndex;
while ((pathSegmentIndex = path.indexOf("/./")) >= 0) {
path = path.substring(0, pathSegmentIndex + 1).concat(path.substring(pathSegmentIndex + 3));
}
// b) If the path ends with "." as a complete path segment,
// that "." is removed.
if (path.endsWith("/.")) {
path = path.substring(0, path.length() - 1);
}
// c) All occurrences of "<segment>/../", where <segment> is a
// complete path segment not equal to "..", are removed.
// Removal of these path segments is performed iteratively,
// removing the leftmost matching pattern on each iteration,
// until no matching pattern remains.
while ((pathSegmentIndex = path.indexOf("/../")) > 0) {
final String pathSegment = path.substring(0, pathSegmentIndex);
final int slashIndex = pathSegment.lastIndexOf('/');
if (slashIndex < 0) {
continue;
}
if (!"..".equals(pathSegment.substring(slashIndex))) {
path = path.substring(0, slashIndex + 1).concat(path.substring(pathSegmentIndex + 4));
}
}
// d) If the path ends with "<segment>/..", where <segment> is a
// complete path segment not equal to "..", that
// "<segment>/.." is removed.
if (path.endsWith("/..")) {
final String pathSegment = path.substring(0, path.length() - 3);
final int slashIndex = pathSegment.lastIndexOf('/');
if (slashIndex >= 0) {
path = path.substring(0, slashIndex + 1);
}
}
path = removeLeadingSlashPoints(path);
url.path_ = path;
// Step 7: The resulting URL components, including any inherited from
// the base URL, are recombined to give the absolute form of
// the embedded URL.
return url;
}
/**
* "/.." at the beginning should be removed as browsers do (not in RFC)
*/
private static String removeLeadingSlashPoints(String path) {
while (path.startsWith("/..")) {
path = path.substring(3);
}
return path;
}
/**
* Class <tt>Url</tt> represents a Uniform Resource Locator.
*
* @author Martin Tamme
*/
private static class Url {
String scheme_;
String location_;
String path_;
String parameters_;
String query_;
String fragment_;
/**
* Creates a <tt>Url</tt> object.
*/
public Url() {
}
/**
* Creates a <tt>Url</tt> object from the specified
* <tt>Url</tt> object.
*
* @param url a <tt>Url</tt> object.
*/
public Url(final Url url) {
scheme_ = url.scheme_;
location_ = url.location_;
path_ = url.path_;
parameters_ = url.parameters_;
query_ = url.query_;
fragment_ = url.fragment_;
}
/**
* Returns a string representation of the <tt>Url</tt> object.
*
* @return a string representation of the <tt>Url</tt> object.
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
if (scheme_ != null) {
sb.append(scheme_);
sb.append(':');
}
if (location_ != null) {
sb.append("//");
sb.append(location_);
}
if (path_ != null) {
sb.append(path_);
}
if (parameters_ != null) {
sb.append(';');
sb.append(parameters_);
}
if (query_ != null) {
sb.append('?');
sb.append(query_);
}
if (fragment_ != null) {
sb.append('#');
sb.append(fragment_);
}
return sb.toString();
}
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/url/UrlResolver.java | Java | asf20 | 19,352 |
package edu.uci.ics.crawler4j.url;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class TLDList {
private final String tldNamesFileName = "tld-names.txt";
private Set<String> tldSet = new HashSet<>();
private static TLDList instance = new TLDList();
private TLDList() {
try {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream(tldNamesFileName);
if (stream == null) {
System.err.println("Couldn't find " + tldNamesFileName);
System.exit(-1);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty() || line.startsWith("//")) {
continue;
}
tldSet.add(line);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static TLDList getInstance() {
return instance;
}
public boolean contains(String str) {
return tldSet.contains(str);
}
}
| 12rohhit-rohit | src/main/java/edu/uci/ics/crawler4j/url/TLDList.java | Java | asf20 | 1,082 |
# Go support for Protocol Buffers - Google's data interchange format
#
# Copyright 2010 The Go Authors. All rights reserved.
# http://code.google.com/p/goprotobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
all: install
install:
go install ./proto
go install ./protoc-gen-go
test:
go test ./proto
make -C protoc-gen-go/testdata test
clean:
go clean ./...
nuke:
go clean -i ./...
regenerate:
make -C protoc-gen-go/descriptor regenerate
make -C protoc-gen-go/plugin regenerate
make -C proto/testdata regenerate
| 1067282423-goproto000 | Makefile | Makefile | bsd | 1,958 |
# Go support for Protocol Buffers - Google's data interchange format
#
# Copyright 2010 The Go Authors. All rights reserved.
# http://code.google.com/p/goprotobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
include $(GOROOT)/src/Make.cmd
test:
cd testdata && make test
| 1067282423-goproto000 | protoc-gen-go/Makefile | Makefile | bsd | 1,705 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
A plugin for the Google protocol buffer compiler to generate Go code.
This plugin takes no options and the protocol buffer file syntax does
not yet define any options for Go, so program does no option evaluation.
That may change.
*/
package main
import (
"io/ioutil"
"os"
"code.google.com/p/goprotobuf/proto"
"code.google.com/p/goprotobuf/protoc-gen-go/generator"
)
func main() {
// Begin by allocating a generator. The request and response structures are stored there
// so we can do error handling easily - the response structure contains the field to
// report failure.
g := generator.New()
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
g.Error(err, "reading input")
}
if err := proto.Unmarshal(data, g.Request); err != nil {
g.Error(err, "parsing input proto")
}
if len(g.Request.FileToGenerate) == 0 {
g.Fail("no files to generate")
}
g.CommandLineParameters(g.Request.GetParameter())
// Create a wrapped version of the Descriptors and EnumDescriptors that
// point to the file that defines them.
g.WrapTypes()
g.SetPackageNames()
g.BuildTypeNameMap()
g.GenerateAllFiles()
// Send back the results.
data, err = proto.Marshal(g.Response)
if err != nil {
g.Error(err, "failed to marshal output proto")
}
_, err = os.Stdout.Write(data)
if err != nil {
g.Error(err, "failed to write output proto")
}
}
| 1067282423-goproto000 | protoc-gen-go/main.go | Go | bsd | 3,041 |
# Go support for Protocol Buffers - Google's data interchange format
#
# Copyright 2010 The Go Authors. All rights reserved.
# http://code.google.com/p/goprotobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
include $(GOROOT)/src/Make.inc
TARG=code.google.com/p/goprotobuf/compiler/generator
GOFILES=\
generator.go\
DEPS=../descriptor ../plugin ../../proto
include $(GOROOT)/src/Make.pkg
| 1067282423-goproto000 | protoc-gen-go/generator/Makefile | Makefile | bsd | 1,825 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
The code generator for the plugin for the Google protocol buffer compiler.
It generates Go code from the protocol buffer description files read by the
main routine.
*/
package generator
import (
"bytes"
"fmt"
"go/parser"
"go/printer"
"go/token"
"log"
"os"
"path"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"code.google.com/p/goprotobuf/proto"
descriptor "code.google.com/p/goprotobuf/protoc-gen-go/descriptor"
plugin "code.google.com/p/goprotobuf/protoc-gen-go/plugin"
)
// A Plugin provides functionality to add to the output during Go code generation,
// such as to produce RPC stubs.
type Plugin interface {
// Name identifies the plugin.
Name() string
// Init is called once after data structures are built but before
// code generation begins.
Init(g *Generator)
// Generate produces the code generated by the plugin for this file,
// except for the imports, by calling the generator's methods P, In, and Out.
Generate(file *FileDescriptor)
// GenerateImports produces the import declarations for this file.
// It is called after Generate.
GenerateImports(file *FileDescriptor)
}
var plugins []Plugin
// RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated.
// It is typically called during initialization.
func RegisterPlugin(p Plugin) {
plugins = append(plugins, p)
}
// Each type we import as a protocol buffer (other than FileDescriptorProto) needs
// a pointer to the FileDescriptorProto that represents it. These types achieve that
// wrapping by placing each Proto inside a struct with the pointer to its File. The
// structs have the same names as their contents, with "Proto" removed.
// FileDescriptor is used to store the things that it points to.
// The file and package name method are common to messages and enums.
type common struct {
file *descriptor.FileDescriptorProto // File this object comes from.
}
// PackageName is name in the package clause in the generated file.
func (c *common) PackageName() string { return uniquePackageOf(c.file) }
func (c *common) File() *descriptor.FileDescriptorProto { return c.file }
// Descriptor represents a protocol buffer message.
type Descriptor struct {
common
*descriptor.DescriptorProto
parent *Descriptor // The containing message, if any.
nested []*Descriptor // Inner messages, if any.
ext []*ExtensionDescriptor // Extensions, if any.
typename []string // Cached typename vector.
index int // The index into the container, whether the file or another message.
path string // The SourceCodeInfo path as comma-separated integers.
group bool
}
// TypeName returns the elements of the dotted type name.
// The package name is not part of this name.
func (d *Descriptor) TypeName() []string {
if d.typename != nil {
return d.typename
}
n := 0
for parent := d; parent != nil; parent = parent.parent {
n++
}
s := make([]string, n, n)
for parent := d; parent != nil; parent = parent.parent {
n--
s[n] = parent.GetName()
}
d.typename = s
return s
}
// EnumDescriptor describes an enum. If it's at top level, its parent will be nil.
// Otherwise it will be the descriptor of the message in which it is defined.
type EnumDescriptor struct {
common
*descriptor.EnumDescriptorProto
parent *Descriptor // The containing message, if any.
typename []string // Cached typename vector.
path string // The SourceCodeInfo path as comma-separated integers.
}
// TypeName returns the elements of the dotted type name.
// The package name is not part of this name.
func (e *EnumDescriptor) TypeName() (s []string) {
if e.typename != nil {
return e.typename
}
name := e.GetName()
if e.parent == nil {
s = make([]string, 1)
} else {
pname := e.parent.TypeName()
s = make([]string, len(pname)+1)
copy(s, pname)
}
s[len(s)-1] = name
e.typename = s
return s
}
// Everything but the last element of the full type name, CamelCased.
// The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... .
func (e *EnumDescriptor) prefix() string {
typeName := e.TypeName()
ccPrefix := CamelCaseSlice(typeName[0:len(typeName)-1]) + "_"
if e.parent == nil {
// If the enum is not part of a message, the prefix is just the type name.
ccPrefix = CamelCase(*e.Name) + "_"
}
return ccPrefix
}
// The integer value of the named constant in this enumerated type.
func (e *EnumDescriptor) integerValueAsString(name string) string {
for _, c := range e.Value {
if c.GetName() == name {
return fmt.Sprint(c.GetNumber())
}
}
log.Fatal("cannot find value for enum constant")
return ""
}
// ExtensionDescriptor describes an extension. If it's at top level, its parent will be nil.
// Otherwise it will be the descriptor of the message in which it is defined.
type ExtensionDescriptor struct {
common
*descriptor.FieldDescriptorProto
parent *Descriptor // The containing message, if any.
}
// TypeName returns the elements of the dotted type name.
// The package name is not part of this name.
func (e *ExtensionDescriptor) TypeName() (s []string) {
name := e.GetName()
if e.parent == nil {
// top-level extension
s = make([]string, 1)
} else {
pname := e.parent.TypeName()
s = make([]string, len(pname)+1)
copy(s, pname)
}
s[len(s)-1] = name
return s
}
// DescName returns the variable name used for the generated descriptor.
func (e *ExtensionDescriptor) DescName() string {
// The full type name.
typeName := e.TypeName()
// Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix.
for i, s := range typeName {
typeName[i] = CamelCase(s)
}
return "E_" + strings.Join(typeName, "_")
}
// ImportedDescriptor describes a type that has been publicly imported from another file.
type ImportedDescriptor struct {
common
o Object
}
func (id *ImportedDescriptor) TypeName() []string { return id.o.TypeName() }
// FileDescriptor describes an protocol buffer descriptor file (.proto).
// It includes slices of all the messages and enums defined within it.
// Those slices are constructed by WrapTypes.
type FileDescriptor struct {
*descriptor.FileDescriptorProto
desc []*Descriptor // All the messages defined in this file.
enum []*EnumDescriptor // All the enums defined in this file.
ext []*ExtensionDescriptor // All the top-level extensions defined in this file.
imp []*ImportedDescriptor // All types defined in files publicly imported by this file.
// Comments, stored as a map of path (comma-separated integers) to the comment.
comments map[string]*descriptor.SourceCodeInfo_Location
// The full list of symbols that are exported,
// as a map from the exported object to its symbols.
// This is used for supporting public imports.
exported map[Object][]symbol
}
// PackageName is the package name we'll use in the generated code to refer to this file.
func (d *FileDescriptor) PackageName() string { return uniquePackageOf(d.FileDescriptorProto) }
// goPackageName returns the Go package name to use in the
// generated Go file. The result explicit reports whether the name
// came from an option go_package statement. If explicit is false,
// the name was derived from the protocol buffer's package statement
// or the input file name.
func (d *FileDescriptor) goPackageName() (name string, explicit bool) {
// Does the file have a "go_package" option?
opts := d.Options
if opts != nil {
if pkg := opts.GetGoPackage(); pkg != "" {
return pkg, true
}
if p := opts.GetGoImportPath(); p != "" {
if i := strings.LastIndex(p, "/"); i >= 0 {
return p[i+1:], true
}
}
}
// Does the file have a package clause?
if pkg := d.GetPackage(); pkg != "" {
return pkg, false
}
// Use the file base name.
return baseName(d.GetName()), false
}
func (d *FileDescriptor) addExport(obj Object, sym symbol) {
d.exported[obj] = append(d.exported[obj], sym)
}
// symbol is an interface representing an exported Go symbol.
type symbol interface {
// GenerateAlias should generate an appropriate alias
// for the symbol from the named package.
GenerateAlias(g *Generator, pkg string)
}
type messageSymbol struct {
sym string
hasExtensions, isMessageSet bool
getters []getterSymbol
}
type getterSymbol struct {
name string
typ string
typeName string // canonical name in proto world; empty for proto.Message and similar
genType bool // whether typ is a generated type (message/group/enum)
}
func (ms *messageSymbol) GenerateAlias(g *Generator, pkg string) {
remoteSym := pkg + "." + ms.sym
g.P("type ", ms.sym, " ", remoteSym)
g.P("func (m *", ms.sym, ") Reset() { (*", remoteSym, ")(m).Reset() }")
g.P("func (m *", ms.sym, ") String() string { return (*", remoteSym, ")(m).String() }")
g.P("func (*", ms.sym, ") ProtoMessage() {}")
if ms.hasExtensions {
g.P("func (*", ms.sym, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange ",
"{ return (*", remoteSym, ")(nil).ExtensionRangeArray() }")
g.P("func (m *", ms.sym, ") ExtensionMap() map[int32]", g.Pkg["proto"], ".Extension ",
"{ return (*", remoteSym, ")(m).ExtensionMap() }")
if ms.isMessageSet {
g.P("func (m *", ms.sym, ") Marshal() ([]byte, error) ",
"{ return (*", remoteSym, ")(m).Marshal() }")
g.P("func (m *", ms.sym, ") Unmarshal(buf []byte) error ",
"{ return (*", remoteSym, ")(m).Unmarshal(buf) }")
}
}
for _, get := range ms.getters {
if get.typeName != "" {
g.RecordTypeUse(get.typeName)
}
typ := get.typ
val := "(*" + remoteSym + ")(m)." + get.name + "()"
if get.genType {
// typ will be "*pkg.T" (message/group) or "pkg.T" (enum).
// Either of those might have a "[]" prefix if it is repeated.
// Drop the package qualifier since we have hoisted the type into this package.
rep := strings.HasPrefix(typ, "[]")
if rep {
typ = typ[2:]
}
star := typ[0] == '*'
typ = typ[strings.Index(typ, ".")+1:]
if star {
typ = "*" + typ
}
if rep {
// Go does not permit conversion between slice types where both
// element types are named. That means we need to generate a bit
// of code in this situation.
// typ is the element type.
// val is the expression to get the slice from the imported type.
ctyp := typ // conversion type expression; "Foo" or "(*Foo)"
if star {
ctyp = "(" + typ + ")"
}
g.P("func (m *", ms.sym, ") ", get.name, "() []", typ, " {")
g.In()
g.P("o := ", val)
g.P("if o == nil {")
g.In()
g.P("return nil")
g.Out()
g.P("}")
g.P("s := make([]", typ, ", len(o))")
g.P("for i, x := range o {")
g.In()
g.P("s[i] = ", ctyp, "(x)")
g.Out()
g.P("}")
g.P("return s")
g.Out()
g.P("}")
continue
}
// Convert imported type into the forwarding type.
val = "(" + typ + ")(" + val + ")"
}
g.P("func (m *", ms.sym, ") ", get.name, "() ", typ, " { return ", val, " }")
}
}
type enumSymbol string
func (es enumSymbol) GenerateAlias(g *Generator, pkg string) {
s := string(es)
g.P("type ", s, " ", pkg, ".", s)
g.P("var ", s, "_name = ", pkg, ".", s, "_name")
g.P("var ", s, "_value = ", pkg, ".", s, "_value")
g.P("func New", s, "(x ", s, ") *", s, " { e := ", s, "(x); return &e }")
}
type constOrVarSymbol struct {
sym string
typ string // either "const" or "var"
}
func (cs constOrVarSymbol) GenerateAlias(g *Generator, pkg string) {
g.P(cs.typ, " ", cs.sym, " = ", pkg, ".", cs.sym)
}
// Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects.
type Object interface {
PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness.
TypeName() []string
File() *descriptor.FileDescriptorProto
}
// Each package name we generate must be unique. The package we're generating
// gets its own name but every other package must have a unique name that does
// not conflict in the code we generate. These names are chosen globally (although
// they don't have to be, it simplifies things to do them globally).
func uniquePackageOf(fd *descriptor.FileDescriptorProto) string {
s, ok := uniquePackageName[fd]
if !ok {
log.Fatal("internal error: no package name defined for " + fd.GetName())
}
return s
}
// Generator is the type whose methods generate the output, stored in the associated response structure.
type Generator struct {
*bytes.Buffer
Request *plugin.CodeGeneratorRequest // The input.
Response *plugin.CodeGeneratorResponse // The output.
Param map[string]string // Command-line parameters.
PackageImportPath string // Go import path of the package we're generating code for
ImportPrefix string // String to prefix to imported package file names.
ImportMap map[string]string // Mapping from import name to generated name
Pkg map[string]string // The names under which we import support packages
packageName string // What we're calling ourselves.
allFiles []*FileDescriptor // All files in the tree
genFiles []*FileDescriptor // Those files we will generate output for.
file *FileDescriptor // The file we are compiling now.
usedPackages map[string]bool // Names of packages used in current file.
typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax.
indent string
}
// New creates a new generator and allocates the request and response protobufs.
func New() *Generator {
g := new(Generator)
g.Buffer = new(bytes.Buffer)
g.Request = new(plugin.CodeGeneratorRequest)
g.Response = new(plugin.CodeGeneratorResponse)
return g
}
// Error reports a problem, including an error, and exits the program.
func (g *Generator) Error(err error, msgs ...string) {
s := strings.Join(msgs, " ") + ":" + err.Error()
log.Print("protoc-gen-go: error:", s)
os.Exit(1)
}
// Fail reports a problem and exits the program.
func (g *Generator) Fail(msgs ...string) {
s := strings.Join(msgs, " ")
log.Print("protoc-gen-go: error:", s)
os.Exit(1)
}
// CommandLineParameters breaks the comma-separated list of key=value pairs
// in the parameter (a member of the request protobuf) into a key/value map.
// It then sets file name mappings defined by those entries.
func (g *Generator) CommandLineParameters(parameter string) {
g.Param = make(map[string]string)
for _, p := range strings.Split(parameter, ",") {
if i := strings.Index(p, "="); i < 0 {
g.Param[p] = ""
} else {
g.Param[p[0:i]] = p[i+1:]
}
}
g.ImportMap = make(map[string]string)
for k, v := range g.Param {
switch k {
case "import_prefix":
g.ImportPrefix = v
case "import_path":
g.PackageImportPath = v
default:
if len(k) > 0 && k[0] == 'M' {
g.ImportMap[k[1:]] = v
}
}
}
}
// DefaultPackageName returns the package name printed for the object.
// If its file is in a different package, it returns the package name we're using for this file, plus ".".
// Otherwise it returns the empty string.
func (g *Generator) DefaultPackageName(obj Object) string {
pkg := obj.PackageName()
if pkg == g.packageName {
return ""
}
opts := obj.File().Options
if opts != nil && g.file.Options != nil &&
*opts.GoImportPath == *g.file.Options.GoImportPath {
return ""
}
return pkg + "."
}
// For each input file, the unique package name to use, underscored.
var uniquePackageName = make(map[*descriptor.FileDescriptorProto]string)
// Package names already registered. Key is the name from the .proto file;
// value is the name that appears in the generated code.
var pkgNamesInUse = make(map[string]bool)
// Create and remember a guaranteed unique package name for this file descriptor.
// Pkg is the candidate name. If f is nil, it's a builtin package like "proto" and
// has no file descriptor.
func RegisterUniquePackageName(pkg string, f *FileDescriptor) string {
// Convert dots to underscores before finding a unique alias.
pkg = strings.Map(badToUnderscore, pkg)
for i, orig := 1, pkg; pkgNamesInUse[pkg]; i++ {
// It's a duplicate; must rename.
pkg = orig + strconv.Itoa(i)
}
// Install it.
pkgNamesInUse[pkg] = true
if f != nil {
uniquePackageName[f.FileDescriptorProto] = pkg
}
return pkg
}
var isGoKeyword = map[string]bool{
"break": true,
"case": true,
"chan": true,
"const": true,
"continue": true,
"default": true,
"else": true,
"defer": true,
"fallthrough": true,
"for": true,
"func": true,
"go": true,
"goto": true,
"if": true,
"import": true,
"interface": true,
"map": true,
"package": true,
"range": true,
"return": true,
"select": true,
"struct": true,
"switch": true,
"type": true,
"var": true,
}
// defaultGoPackage returns the package name to use,
// derived from the import path of the package we're building code for.
func (g *Generator) defaultGoPackage() string {
p := g.PackageImportPath
if i := strings.LastIndex(p, "/"); i >= 0 {
p = p[i+1:]
}
if p == "" {
return ""
}
p = strings.Map(badToUnderscore, p)
// Identifier must not be keyword: insert _.
if isGoKeyword[p] {
p = "_" + p
}
// Identifier must not begin with digit: insert _.
if r, _ := utf8.DecodeRuneInString(p); unicode.IsDigit(r) {
p = "_" + p
}
return p
}
// SetPackageNames sets the package name for this run.
// The package name must agree across all files being generated.
// It also defines unique package names for all imported files.
func (g *Generator) SetPackageNames() {
// Register the name for this package. It will be the first name
// registered so is guaranteed to be unmodified.
pkg, explicit := g.genFiles[0].goPackageName()
// Check all files for an explicit go_package option.
for _, f := range g.genFiles {
thisPkg, thisExplicit := f.goPackageName()
if thisExplicit {
if !explicit {
// Let this file's go_package option serve for all input files.
pkg, explicit = thisPkg, true
} else if thisPkg != pkg {
g.Fail("inconsistent package names:", thisPkg, pkg)
}
}
}
// If we don't have an explicit go_package option but we have an
// import path, use that.
if !explicit {
p := g.defaultGoPackage()
if p != "" {
pkg, explicit = p, true
}
}
// If there was no go_package and no import path to use,
// double-check that all the inputs have the same implicit
// Go package name.
if !explicit {
for _, f := range g.genFiles {
thisPkg, _ := f.goPackageName()
if thisPkg != pkg {
g.Fail("inconsistent package names:", thisPkg, pkg)
}
}
}
g.packageName = RegisterUniquePackageName(pkg, g.genFiles[0])
// Register the support package names. They might collide with the
// name of a package we import.
g.Pkg = map[string]string{
"json": RegisterUniquePackageName("json", nil),
"math": RegisterUniquePackageName("math", nil),
"proto": RegisterUniquePackageName("proto", nil),
}
AllFiles:
for _, f := range g.allFiles {
for _, genf := range g.genFiles {
if f == genf {
// In this package already.
uniquePackageName[f.FileDescriptorProto] = g.packageName
continue AllFiles
}
}
// The file is a dependency, so we want to ignore its go_package option
// because that is only relevant for its specific generated output.
pkg := f.GetPackage()
if pkg == "" {
pkg = baseName(*f.Name)
}
RegisterUniquePackageName(pkg, f)
}
}
// WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos
// and FileDescriptorProtos into file-referenced objects within the Generator.
// It also creates the list of files to generate and so should be called before GenerateAllFiles.
func (g *Generator) WrapTypes() {
g.allFiles = make([]*FileDescriptor, len(g.Request.ProtoFile))
for i, f := range g.Request.ProtoFile {
// We must wrap the descriptors before we wrap the enums
descs := wrapDescriptors(f)
g.buildNestedDescriptors(descs)
enums := wrapEnumDescriptors(f, descs)
exts := wrapExtensions(f)
imps := wrapImported(f, g)
fd := &FileDescriptor{
FileDescriptorProto: f,
desc: descs,
enum: enums,
ext: exts,
imp: imps,
exported: make(map[Object][]symbol),
}
extractComments(fd)
g.allFiles[i] = fd
}
g.genFiles = make([]*FileDescriptor, len(g.Request.FileToGenerate))
FindFiles:
for i, fileName := range g.Request.FileToGenerate {
// Search the list. This algorithm is n^2 but n is tiny.
for _, file := range g.allFiles {
if fileName == file.GetName() {
g.genFiles[i] = file
continue FindFiles
}
}
g.Fail("could not find file named", fileName)
}
g.Response.File = make([]*plugin.CodeGeneratorResponse_File, len(g.genFiles))
}
// Scan the descriptors in this file. For each one, build the slice of nested descriptors
func (g *Generator) buildNestedDescriptors(descs []*Descriptor) {
for _, desc := range descs {
if len(desc.NestedType) != 0 {
desc.nested = make([]*Descriptor, len(desc.NestedType))
n := 0
for _, nest := range descs {
if nest.parent == desc {
desc.nested[n] = nest
n++
}
}
if n != len(desc.NestedType) {
g.Fail("internal error: nesting failure for", desc.GetName())
}
}
}
}
// Construct the Descriptor
func newDescriptor(desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *Descriptor {
d := &Descriptor{
common: common{file},
DescriptorProto: desc,
parent: parent,
index: index,
}
if parent == nil {
d.path = fmt.Sprintf("%d,%d", messagePath, index)
} else {
d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index)
}
// The only way to distinguish a group from a message is whether
// the containing message has a TYPE_GROUP field that matches.
if parent != nil {
parts := d.TypeName()
if file.Package != nil {
parts = append([]string{*file.Package}, parts...)
}
exp := "." + strings.Join(parts, ".")
for _, field := range parent.Field {
if field.GetType() == descriptor.FieldDescriptorProto_TYPE_GROUP && field.GetTypeName() == exp {
d.group = true
break
}
}
}
d.ext = make([]*ExtensionDescriptor, len(desc.Extension))
for i, field := range desc.Extension {
d.ext[i] = &ExtensionDescriptor{common{file}, field, d}
}
return d
}
// Return a slice of all the Descriptors defined within this file
func wrapDescriptors(file *descriptor.FileDescriptorProto) []*Descriptor {
sl := make([]*Descriptor, 0, len(file.MessageType)+10)
for i, desc := range file.MessageType {
sl = wrapThisDescriptor(sl, desc, nil, file, i)
}
return sl
}
// Wrap this Descriptor, recursively
func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) []*Descriptor {
sl = append(sl, newDescriptor(desc, parent, file, index))
me := sl[len(sl)-1]
for i, nested := range desc.NestedType {
sl = wrapThisDescriptor(sl, nested, me, file, i)
}
return sl
}
// Construct the EnumDescriptor
func newEnumDescriptor(desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *EnumDescriptor {
ed := &EnumDescriptor{
common: common{file},
EnumDescriptorProto: desc,
parent: parent,
}
if parent == nil {
ed.path = fmt.Sprintf("%d,%d", enumPath, index)
} else {
ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index)
}
return ed
}
// Return a slice of all the EnumDescriptors defined within this file
func wrapEnumDescriptors(file *descriptor.FileDescriptorProto, descs []*Descriptor) []*EnumDescriptor {
sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10)
// Top-level enums.
for i, enum := range file.EnumType {
sl = append(sl, newEnumDescriptor(enum, nil, file, i))
}
// Enums within messages. Enums within embedded messages appear in the outer-most message.
for _, nested := range descs {
for i, enum := range nested.EnumType {
sl = append(sl, newEnumDescriptor(enum, nested, file, i))
}
}
return sl
}
// Return a slice of all the top-level ExtensionDescriptors defined within this file.
func wrapExtensions(file *descriptor.FileDescriptorProto) []*ExtensionDescriptor {
sl := make([]*ExtensionDescriptor, len(file.Extension))
for i, field := range file.Extension {
sl[i] = &ExtensionDescriptor{common{file}, field, nil}
}
return sl
}
// Return a slice of all the types that are publicly imported into this file.
func wrapImported(file *descriptor.FileDescriptorProto, g *Generator) (sl []*ImportedDescriptor) {
for _, index := range file.PublicDependency {
df := g.fileByName(file.Dependency[index])
for _, d := range df.desc {
sl = append(sl, &ImportedDescriptor{common{file}, d})
}
for _, e := range df.enum {
sl = append(sl, &ImportedDescriptor{common{file}, e})
}
for _, ext := range df.ext {
sl = append(sl, &ImportedDescriptor{common{file}, ext})
}
}
return
}
func extractComments(file *FileDescriptor) {
file.comments = make(map[string]*descriptor.SourceCodeInfo_Location)
for _, loc := range file.GetSourceCodeInfo().GetLocation() {
if loc.LeadingComments == nil {
continue
}
var p []string
for _, n := range loc.Path {
p = append(p, strconv.Itoa(int(n)))
}
file.comments[strings.Join(p, ",")] = loc
}
}
// BuildTypeNameMap builds the map from fully qualified type names to objects.
// The key names for the map come from the input data, which puts a period at the beginning.
// It should be called after SetPackageNames and before GenerateAllFiles.
func (g *Generator) BuildTypeNameMap() {
g.typeNameToObject = make(map[string]Object)
for _, f := range g.allFiles {
// The names in this loop are defined by the proto world, not us, so the
// package name may be empty. If so, the dotted package name of X will
// be ".X"; otherwise it will be ".pkg.X".
dottedPkg := "." + f.GetPackage()
if dottedPkg != "." {
dottedPkg += "."
}
for _, enum := range f.enum {
name := dottedPkg + dottedSlice(enum.TypeName())
g.typeNameToObject[name] = enum
}
for _, desc := range f.desc {
name := dottedPkg + dottedSlice(desc.TypeName())
g.typeNameToObject[name] = desc
}
}
}
// ObjectNamed, given a fully-qualified input type name as it appears in the input data,
// returns the descriptor for the message or enum with that name.
func (g *Generator) ObjectNamed(typeName string) Object {
o, ok := g.typeNameToObject[typeName]
if !ok {
g.Fail("can't find object with type", typeName)
}
// If the file of this object isn't a direct dependency of the current file,
// or in the current file, then this object has been publicly imported into
// a dependency of the current file.
// We should return the ImportedDescriptor object for it instead.
direct := *o.File().Name == *g.file.Name
if !direct {
for _, dep := range g.file.Dependency {
if *g.fileByName(dep).Name == *o.File().Name {
direct = true
break
}
}
}
if !direct {
found := false
Loop:
for _, dep := range g.file.Dependency {
df := g.fileByName(*g.fileByName(dep).Name)
for _, td := range df.imp {
if td.o == o {
// Found it!
o = td
found = true
break Loop
}
}
}
if !found {
log.Printf("protoc-gen-go: WARNING: failed finding publicly imported dependency for %v, used in %v", typeName, *g.file.Name)
}
}
return o
}
// P prints the arguments to the generated output. It handles strings and int32s, plus
// handling indirections because they may be *string, etc.
func (g *Generator) P(str ...interface{}) {
g.WriteString(g.indent)
for _, v := range str {
switch s := v.(type) {
case string:
g.WriteString(s)
case *string:
g.WriteString(*s)
case bool:
g.WriteString(fmt.Sprintf("%t", s))
case *bool:
g.WriteString(fmt.Sprintf("%t", *s))
case int:
g.WriteString(fmt.Sprintf("%d", s))
case *int32:
g.WriteString(fmt.Sprintf("%d", *s))
case *int64:
g.WriteString(fmt.Sprintf("%d", *s))
case float64:
g.WriteString(fmt.Sprintf("%g", s))
case *float64:
g.WriteString(fmt.Sprintf("%g", *s))
default:
g.Fail(fmt.Sprintf("unknown type in printer: %T", v))
}
}
g.WriteByte('\n')
}
// In Indents the output one tab stop.
func (g *Generator) In() { g.indent += "\t" }
// Out unindents the output one tab stop.
func (g *Generator) Out() {
if len(g.indent) > 0 {
g.indent = g.indent[1:]
}
}
// GenerateAllFiles generates the output for all the files we're outputting.
func (g *Generator) GenerateAllFiles() {
// Initialize the plugins
for _, p := range plugins {
p.Init(g)
}
// Generate the output. The generator runs for every file, even the files
// that we don't generate output for, so that we can collate the full list
// of exported symbols to support public imports.
genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles))
for _, file := range g.genFiles {
genFileMap[file] = true
}
i := 0
for _, file := range g.allFiles {
g.Reset()
g.generate(file)
if _, ok := genFileMap[file]; !ok {
continue
}
g.Response.File[i] = new(plugin.CodeGeneratorResponse_File)
g.Response.File[i].Name = proto.String(goFileName(*file.Name))
g.Response.File[i].Content = proto.String(g.String())
i++
}
}
// Run all the plugins associated with the file.
func (g *Generator) runPlugins(file *FileDescriptor) {
for _, p := range plugins {
p.Generate(file)
}
}
// FileOf return the FileDescriptor for this FileDescriptorProto.
func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor {
for _, file := range g.allFiles {
if file.FileDescriptorProto == fd {
return file
}
}
g.Fail("could not find file in table:", fd.GetName())
return nil
}
// Fill the response protocol buffer with the generated output for all the files we're
// supposed to generate.
func (g *Generator) generate(file *FileDescriptor) {
g.file = g.FileOf(file.FileDescriptorProto)
g.usedPackages = make(map[string]bool)
for _, td := range g.file.imp {
g.generateImported(td)
}
for _, enum := range g.file.enum {
g.generateEnum(enum)
}
for _, desc := range g.file.desc {
g.generateMessage(desc)
}
for _, ext := range g.file.ext {
g.generateExtension(ext)
}
g.generateInitFunction()
// Run the plugins before the imports so we know which imports are necessary.
g.runPlugins(file)
// Generate header and imports last, though they appear first in the output.
rem := g.Buffer
g.Buffer = new(bytes.Buffer)
g.generateHeader()
g.generateImports()
g.Write(rem.Bytes())
// Reformat generated code.
fset := token.NewFileSet()
ast, err := parser.ParseFile(fset, "", g, parser.ParseComments)
if err != nil {
g.Fail("bad Go source code was generated:", err.Error())
return
}
g.Reset()
err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast)
if err != nil {
g.Fail("generated Go source code could not be reformatted:", err.Error())
}
}
// Generate the header, including package definition
func (g *Generator) generateHeader() {
g.P("// Code generated by protoc-gen-go.")
g.P("// source: ", *g.file.Name)
g.P("// DO NOT EDIT!")
g.P()
g.P("package ", g.file.PackageName())
g.P()
}
// PrintComments prints any comments from the source .proto file.
// The path is a comma-separated list of integers.
// See descriptor.proto for its format.
func (g *Generator) PrintComments(path string) {
if loc, ok := g.file.comments[path]; ok {
text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
for _, line := range strings.Split(text, "\n") {
g.P("// ", strings.TrimPrefix(line, " "))
}
}
}
func (g *Generator) fileByName(filename string) *FileDescriptor {
for _, fd := range g.allFiles {
if fd.GetName() == filename {
return fd
}
}
return nil
}
// weak returns whether the ith import of the current file is a weak import.
func (g *Generator) weak(i int32) bool {
for _, j := range g.file.WeakDependency {
if j == i {
return true
}
}
return false
}
// Generate the imports
func (g *Generator) generateImports() {
// We almost always need a proto import. Rather than computing when we
// do, which is tricky when there's a plugin, just import it and
// reference it later. The same argument applies to the math package,
// for handling bit patterns for floating-point numbers, and to the
// json package, for symbolic names of enum values for JSON marshaling.
g.P("import " + g.Pkg["proto"] + " " + strconv.Quote(g.ImportPrefix+"code.google.com/p/goprotobuf/proto"))
g.P("import " + g.Pkg["json"] + ` "encoding/json"`)
g.P("import " + g.Pkg["math"] + ` "math"`)
for i, s := range g.file.Dependency {
fd := g.fileByName(s)
// Do not import our own package.
if fd.PackageName() == g.packageName {
continue
}
filename := goFileName(s)
if substitution, ok := g.ImportMap[s]; ok {
filename = substitution
}
filename = g.ImportPrefix + filename
if strings.HasSuffix(filename, ".go") {
filename = filename[0 : len(filename)-3]
}
// Skip weak imports.
if g.weak(int32(i)) {
g.P("// skipping weak import ", fd.PackageName(), " ", strconv.Quote(filename))
continue
}
if _, ok := g.usedPackages[fd.PackageName()]; ok {
if opts := fd.Options; opts != nil && opts.GoImportPath != nil {
if g.file.Options != nil && *g.file.Options.GoImportPath != *opts.GoImportPath {
g.P("import ", fd.PackageName(), " ", strconv.Quote(*opts.GoImportPath))
}
} else {
g.P("import ", fd.PackageName(), " ", strconv.Quote(filename))
}
} else {
// TODO: Re-enable this when we are more feature-complete.
// For instance, some protos use foreign field extensions, which we don't support.
// Until then, this is just annoying spam.
//log.Printf("protoc-gen-go: discarding unused import from %v: %v", *g.file.Name, s)
g.P("// discarding unused import ", fd.PackageName(), " ", strconv.Quote(filename))
}
}
g.P()
// TODO: may need to worry about uniqueness across plugins
for _, p := range plugins {
p.GenerateImports(g.file)
g.P()
}
g.P("// Reference proto, json, and math imports to suppress error if they are not otherwise used.")
g.P("var _ = ", g.Pkg["proto"], ".Marshal")
g.P("var _ = &", g.Pkg["json"], ".SyntaxError{}")
g.P("var _ = ", g.Pkg["math"], ".Inf")
g.P()
}
func (g *Generator) generateImported(id *ImportedDescriptor) {
// Don't generate public import symbols for files that we are generating
// code for, since those symbols will already be in this package.
// We can't simply avoid creating the ImportedDescriptor objects,
// because g.genFiles isn't populated at that stage.
tn := id.TypeName()
sn := tn[len(tn)-1]
df := g.FileOf(id.o.File())
filename := *df.Name
for _, fd := range g.genFiles {
if *fd.Name == filename {
g.P("// Ignoring public import of ", sn, " from ", filename)
g.P()
return
}
}
g.P("// ", sn, " from public import ", filename)
g.usedPackages[df.PackageName()] = true
for _, sym := range df.exported[id.o] {
sym.GenerateAlias(g, df.PackageName())
}
g.P()
}
// Generate the enum definitions for this EnumDescriptor.
func (g *Generator) generateEnum(enum *EnumDescriptor) {
// The full type name
typeName := enum.TypeName()
// The full type name, CamelCased.
ccTypeName := CamelCaseSlice(typeName)
ccPrefix := enum.prefix()
g.PrintComments(enum.path)
g.P("type ", ccTypeName, " int32")
g.file.addExport(enum, enumSymbol(ccTypeName))
g.P("const (")
g.In()
for i, e := range enum.Value {
g.PrintComments(fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i))
name := ccPrefix + *e.Name
g.P(name, " ", ccTypeName, " = ", e.Number)
g.file.addExport(enum, constOrVarSymbol{name, "const"})
}
g.Out()
g.P(")")
g.P("var ", ccTypeName, "_name = map[int32]string{")
g.In()
generated := make(map[int32]bool) // avoid duplicate values
for _, e := range enum.Value {
duplicate := ""
if _, present := generated[*e.Number]; present {
duplicate = "// Duplicate value: "
}
g.P(duplicate, e.Number, ": ", strconv.Quote(*e.Name), ",")
generated[*e.Number] = true
}
g.Out()
g.P("}")
g.P("var ", ccTypeName, "_value = map[string]int32{")
g.In()
for _, e := range enum.Value {
g.P(strconv.Quote(*e.Name), ": ", e.Number, ",")
}
g.Out()
g.P("}")
g.P("func (x ", ccTypeName, ") Enum() *", ccTypeName, " {")
g.In()
g.P("p := new(", ccTypeName, ")")
g.P("*p = x")
g.P("return p")
g.Out()
g.P("}")
g.P("func (x ", ccTypeName, ") String() string {")
g.In()
g.P("return ", g.Pkg["proto"], ".EnumName(", ccTypeName, "_name, int32(x))")
g.Out()
g.P("}")
g.P("func (x ", ccTypeName, ") MarshalJSON() ([]byte, error) {")
g.In()
g.P("return json.Marshal(x.String())")
g.Out()
g.P("}")
g.P("func (x *", ccTypeName, ") UnmarshalJSON(data []byte) error {")
g.In()
g.P("value, err := ", g.Pkg["proto"], ".UnmarshalJSONEnum(", ccTypeName, `_value, data, "`, ccTypeName, `")`)
g.P("if err != nil {")
g.In()
g.P("return err")
g.Out()
g.P("}")
g.P("*x = ", ccTypeName, "(value)")
g.P("return nil")
g.Out()
g.P("}")
g.P()
}
// The tag is a string like "varint,2,opt,name=fieldname,def=7" that
// identifies details of the field for the protocol buffer marshaling and unmarshaling
// code. The fields are:
// wire encoding
// protocol tag number
// opt,req,rep for optional, required, or repeated
// packed whether the encoding is "packed" (optional; repeated primitives only)
// name= the original declared name
// enum= the name of the enum type if it is an enum-typed field.
// def= string representation of the default value, if any.
// The default value must be in a representation that can be used at run-time
// to generate the default value. Thus bools become 0 and 1, for instance.
func (g *Generator) goTag(field *descriptor.FieldDescriptorProto, wiretype string) string {
optrepreq := ""
switch {
case isOptional(field):
optrepreq = "opt"
case isRequired(field):
optrepreq = "req"
case isRepeated(field):
optrepreq = "rep"
}
defaultValue := field.GetDefaultValue()
if defaultValue != "" {
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_BOOL:
if defaultValue == "true" {
defaultValue = "1"
} else {
defaultValue = "0"
}
case descriptor.FieldDescriptorProto_TYPE_STRING,
descriptor.FieldDescriptorProto_TYPE_BYTES:
// Nothing to do. Quoting is done for the whole tag.
case descriptor.FieldDescriptorProto_TYPE_ENUM:
// For enums we need to provide the integer constant.
obj := g.ObjectNamed(field.GetTypeName())
enum, ok := obj.(*EnumDescriptor)
if !ok {
g.Fail("enum type inconsistent for", CamelCaseSlice(obj.TypeName()))
}
defaultValue = enum.integerValueAsString(defaultValue)
}
defaultValue = ",def=" + defaultValue
}
enum := ""
if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM {
// We avoid using obj.PackageName(), because we want to use the
// original (proto-world) package name.
obj := g.ObjectNamed(field.GetTypeName())
enum = ",enum="
if pkg := obj.File().GetPackage(); pkg != "" {
enum += pkg + "."
}
enum += CamelCaseSlice(obj.TypeName())
}
packed := ""
if field.Options != nil && field.Options.GetPacked() {
packed = ",packed"
}
fieldName := field.GetName()
name := fieldName
if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP {
// We must use the type name for groups instead of
// the field name to preserve capitalization.
// type_name in FieldDescriptorProto is fully-qualified,
// but we only want the local part.
name = *field.TypeName
if i := strings.LastIndex(name, "."); i >= 0 {
name = name[i+1:]
}
}
if name == CamelCase(fieldName) {
name = ""
} else {
name = ",name=" + name
}
return strconv.Quote(fmt.Sprintf("%s,%d,%s%s%s%s%s",
wiretype,
field.GetNumber(),
optrepreq,
packed,
name,
enum,
defaultValue))
}
func needsStar(typ descriptor.FieldDescriptorProto_Type) bool {
switch typ {
case descriptor.FieldDescriptorProto_TYPE_GROUP:
return false
case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
return false
case descriptor.FieldDescriptorProto_TYPE_BYTES:
return false
}
return true
}
// TypeName is the printed name appropriate for an item. If the object is in the current file,
// TypeName drops the package name and underscores the rest.
// Otherwise the object is from another package; and the result is the underscored
// package name followed by the item name.
// The result always has an initial capital.
func (g *Generator) TypeName(obj Object) string {
return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName())
}
// TypeNameWithPackage is like TypeName, but always includes the package
// name even if the object is in our own package.
func (g *Generator) TypeNameWithPackage(obj Object) string {
return obj.PackageName() + CamelCaseSlice(obj.TypeName())
}
// GoType returns a string representing the type name, and the wire type
func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) {
// TODO: Options.
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
typ, wire = "float64", "fixed64"
case descriptor.FieldDescriptorProto_TYPE_FLOAT:
typ, wire = "float32", "fixed32"
case descriptor.FieldDescriptorProto_TYPE_INT64:
typ, wire = "int64", "varint"
case descriptor.FieldDescriptorProto_TYPE_UINT64:
typ, wire = "uint64", "varint"
case descriptor.FieldDescriptorProto_TYPE_INT32:
typ, wire = "int32", "varint"
case descriptor.FieldDescriptorProto_TYPE_UINT32:
typ, wire = "uint32", "varint"
case descriptor.FieldDescriptorProto_TYPE_FIXED64:
typ, wire = "uint64", "fixed64"
case descriptor.FieldDescriptorProto_TYPE_FIXED32:
typ, wire = "uint32", "fixed32"
case descriptor.FieldDescriptorProto_TYPE_BOOL:
typ, wire = "bool", "varint"
case descriptor.FieldDescriptorProto_TYPE_STRING:
typ, wire = "string", "bytes"
case descriptor.FieldDescriptorProto_TYPE_GROUP:
desc := g.ObjectNamed(field.GetTypeName())
typ, wire = "*"+g.TypeName(desc), "group"
case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
desc := g.ObjectNamed(field.GetTypeName())
typ, wire = "*"+g.TypeName(desc), "bytes"
case descriptor.FieldDescriptorProto_TYPE_BYTES:
typ, wire = "[]byte", "bytes"
case descriptor.FieldDescriptorProto_TYPE_ENUM:
desc := g.ObjectNamed(field.GetTypeName())
typ, wire = g.TypeName(desc), "varint"
case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
typ, wire = "int32", "fixed32"
case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
typ, wire = "int64", "fixed64"
case descriptor.FieldDescriptorProto_TYPE_SINT32:
typ, wire = "int32", "zigzag32"
case descriptor.FieldDescriptorProto_TYPE_SINT64:
typ, wire = "int64", "zigzag64"
default:
g.Fail("unknown type for", field.GetName())
}
if isRepeated(field) {
typ = "[]" + typ
} else if needsStar(*field.Type) {
typ = "*" + typ
}
return
}
func (g *Generator) RecordTypeUse(t string) {
if obj, ok := g.typeNameToObject[t]; ok {
// Call ObjectNamed to get the true object to record the use.
obj = g.ObjectNamed(t)
g.usedPackages[obj.PackageName()] = true
}
}
// Method names that may be generated. Fields with these names get an
// underscore appended.
var methodNames = [...]string{
"Reset",
"String",
"ProtoMessage",
"Marshal",
"Unmarshal",
"ExtensionRangeArray",
"ExtensionMap",
"Descriptor",
}
// Generate the type and default constant definitions for this Descriptor.
func (g *Generator) generateMessage(message *Descriptor) {
// The full type name
typeName := message.TypeName()
// The full type name, CamelCased.
ccTypeName := CamelCaseSlice(typeName)
usedNames := make(map[string]bool)
for _, n := range methodNames {
usedNames[n] = true
}
fieldNames := make(map[*descriptor.FieldDescriptorProto]string)
fieldGetterNames := make(map[*descriptor.FieldDescriptorProto]string)
g.PrintComments(message.path)
g.P("type ", ccTypeName, " struct {")
g.In()
for i, field := range message.Field {
g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i))
fieldName := CamelCase(*field.Name)
for usedNames[fieldName] {
fieldName += "_"
}
fieldGetterName := fieldName
usedNames[fieldName] = true
typename, wiretype := g.GoType(message, field)
jsonName := *field.Name
tag := fmt.Sprintf("protobuf:%s json:%q", g.goTag(field, wiretype), jsonName+",omitempty")
fieldNames[field] = fieldName
fieldGetterNames[field] = fieldGetterName
g.P(fieldName, "\t", typename, "\t`", tag, "`")
g.RecordTypeUse(field.GetTypeName())
}
if len(message.ExtensionRange) > 0 {
g.P("XXX_extensions\t\tmap[int32]", g.Pkg["proto"], ".Extension `json:\"-\"`")
}
g.P("XXX_unrecognized\t[]byte `json:\"-\"`")
g.Out()
g.P("}")
// Reset, String and ProtoMessage methods.
g.P("func (m *", ccTypeName, ") Reset() { *m = ", ccTypeName, "{} }")
g.P("func (m *", ccTypeName, ") String() string { return ", g.Pkg["proto"], ".CompactTextString(m) }")
g.P("func (*", ccTypeName, ") ProtoMessage() {}")
// Extension support methods
var hasExtensions, isMessageSet bool
if len(message.ExtensionRange) > 0 {
hasExtensions = true
// message_set_wire_format only makes sense when extensions are defined.
if opts := message.Options; opts != nil && opts.GetMessageSetWireFormat() {
isMessageSet = true
g.P()
g.P("func (m *", ccTypeName, ") Marshal() ([]byte, error) {")
g.In()
g.P("return ", g.Pkg["proto"], ".MarshalMessageSet(m.ExtensionMap())")
g.Out()
g.P("}")
g.P("func (m *", ccTypeName, ") Unmarshal(buf []byte) error {")
g.In()
g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSet(buf, m.ExtensionMap())")
g.Out()
g.P("}")
g.P("// ensure ", ccTypeName, " satisfies proto.Marshaler and proto.Unmarshaler")
g.P("var _ ", g.Pkg["proto"], ".Marshaler = (*", ccTypeName, ")(nil)")
g.P("var _ ", g.Pkg["proto"], ".Unmarshaler = (*", ccTypeName, ")(nil)")
}
g.P()
g.P("var extRange_", ccTypeName, " = []", g.Pkg["proto"], ".ExtensionRange{")
g.In()
for _, r := range message.ExtensionRange {
end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends
g.P("{", r.Start, ", ", end, "},")
}
g.Out()
g.P("}")
g.P("func (*", ccTypeName, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange {")
g.In()
g.P("return extRange_", ccTypeName)
g.Out()
g.P("}")
g.P("func (m *", ccTypeName, ") ExtensionMap() map[int32]", g.Pkg["proto"], ".Extension {")
g.In()
g.P("if m.XXX_extensions == nil {")
g.In()
g.P("m.XXX_extensions = make(map[int32]", g.Pkg["proto"], ".Extension)")
g.Out()
g.P("}")
g.P("return m.XXX_extensions")
g.Out()
g.P("}")
}
// Default constants
defNames := make(map[*descriptor.FieldDescriptorProto]string)
for _, field := range message.Field {
def := field.GetDefaultValue()
if def == "" {
continue
}
fieldname := "Default_" + ccTypeName + "_" + CamelCase(*field.Name)
defNames[field] = fieldname
typename, _ := g.GoType(message, field)
if typename[0] == '*' {
typename = typename[1:]
}
kind := "const "
switch {
case typename == "bool":
case typename == "string":
def = strconv.Quote(def)
case typename == "[]byte":
def = "[]byte(" + strconv.Quote(def) + ")"
kind = "var "
case def == "inf", def == "-inf", def == "nan":
// These names are known to, and defined by, the protocol language.
switch def {
case "inf":
def = "math.Inf(1)"
case "-inf":
def = "math.Inf(-1)"
case "nan":
def = "math.NaN()"
}
if *field.Type == descriptor.FieldDescriptorProto_TYPE_FLOAT {
def = "float32(" + def + ")"
}
kind = "var "
case *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM:
// Must be an enum. Need to construct the prefixed name.
obj := g.ObjectNamed(field.GetTypeName())
enum, ok := obj.(*EnumDescriptor)
if !ok {
log.Print("don't know how to generate constant for", fieldname)
continue
}
def = g.DefaultPackageName(enum) + enum.prefix() + def
}
g.P(kind, fieldname, " ", typename, " = ", def)
g.file.addExport(message, constOrVarSymbol{fieldname, kind})
}
g.P()
// Field getters
var getters []getterSymbol
for _, field := range message.Field {
fname := fieldNames[field]
typename, _ := g.GoType(message, field)
mname := "Get" + fieldGetterNames[field]
star := ""
if needsStar(*field.Type) && typename[0] == '*' {
typename = typename[1:]
star = "*"
}
// Only export getter symbols for basic types,
// and for messages and enums in the same package.
// Groups are not exported.
// Foreign types can't be hoisted through a public import because
// the importer may not already be importing the defining .proto.
// As an example, imagine we have an import tree like this:
// A.proto -> B.proto -> C.proto
// If A publicly imports B, we need to generate the getters from B in A's output,
// but if one such getter returns something from C then we cannot do that
// because A is not importing C already.
var getter, genType bool
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_GROUP:
getter = false
case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_ENUM:
// Only export getter if its return type is in this package.
getter = g.ObjectNamed(field.GetTypeName()).PackageName() == message.PackageName()
genType = true
default:
getter = true
}
if getter {
getters = append(getters, getterSymbol{
name: mname,
typ: typename,
typeName: field.GetTypeName(),
genType: genType,
})
}
g.P("func (m *", ccTypeName, ") "+mname+"() "+typename+" {")
g.In()
def, hasDef := defNames[field]
typeDefaultIsNil := false // whether this field type's default value is a literal nil unless specified
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_BYTES:
typeDefaultIsNil = !hasDef
case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE:
typeDefaultIsNil = true
}
if isRepeated(field) {
typeDefaultIsNil = true
}
if typeDefaultIsNil {
// A bytes field with no explicit default needs less generated code,
// as does a message or group field, or a repeated field.
g.P("if m != nil {")
g.In()
g.P("return m." + fname)
g.Out()
g.P("}")
g.P("return nil")
g.Out()
g.P("}")
g.P()
continue
}
g.P("if m != nil && m." + fname + " != nil {")
g.In()
g.P("return " + star + "m." + fname)
g.Out()
g.P("}")
if hasDef {
if *field.Type != descriptor.FieldDescriptorProto_TYPE_BYTES {
g.P("return " + def)
} else {
// The default is a []byte var.
// Make a copy when returning it to be safe.
g.P("return append([]byte(nil), ", def, "...)")
}
} else {
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_BOOL:
g.P("return false")
case descriptor.FieldDescriptorProto_TYPE_STRING:
g.P(`return ""`)
default:
g.P("return 0")
}
}
g.Out()
g.P("}")
g.P()
}
if !message.group {
g.file.addExport(message, &messageSymbol{ccTypeName, hasExtensions, isMessageSet, getters})
}
for _, ext := range message.ext {
g.generateExtension(ext)
}
}
func (g *Generator) generateExtension(ext *ExtensionDescriptor) {
ccTypeName := ext.DescName()
extendedType := "*" + g.TypeName(g.ObjectNamed(*ext.Extendee))
field := ext.FieldDescriptorProto
fieldType, wireType := g.GoType(ext.parent, field)
tag := g.goTag(field, wireType)
g.RecordTypeUse(*ext.Extendee)
if n := ext.FieldDescriptorProto.TypeName; n != nil {
// foreign extension type
g.RecordTypeUse(*n)
}
typeName := ext.TypeName()
// Special case for proto2 message sets: If this extension is extending
// proto2_bridge.MessageSet, and its final name component is "message_set_extension",
// then drop that last component.
if extendedType == "*proto2_bridge.MessageSet" && typeName[len(typeName)-1] == "message_set_extension" {
typeName = typeName[:len(typeName)-1]
}
// For text formatting, the package must be exactly what the .proto file declares,
// ignoring overrides such as the go_package option, and with no dot/underscore mapping.
extName := strings.Join(typeName, ".")
if g.file.Package != nil {
extName = *g.file.Package + "." + extName
}
g.P("var ", ccTypeName, " = &", g.Pkg["proto"], ".ExtensionDesc{")
g.In()
g.P("ExtendedType: (", extendedType, ")(nil),")
g.P("ExtensionType: (", fieldType, ")(nil),")
g.P("Field: ", field.Number, ",")
g.P(`Name: "`, extName, `",`)
g.P("Tag: ", tag, ",")
g.Out()
g.P("}")
g.P()
g.file.addExport(ext, constOrVarSymbol{ccTypeName, "var"})
}
func (g *Generator) generateInitFunction() {
g.P("func init() {")
g.In()
for _, enum := range g.file.enum {
g.generateEnumRegistration(enum)
}
for _, d := range g.file.desc {
for _, ext := range d.ext {
g.generateExtensionRegistration(ext)
}
}
for _, ext := range g.file.ext {
g.generateExtensionRegistration(ext)
}
g.Out()
g.P("}")
}
func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) {
// // We always print the full (proto-world) package name here.
pkg := enum.File().GetPackage()
if pkg != "" {
pkg += "."
}
// The full type name
typeName := enum.TypeName()
// The full type name, CamelCased.
ccTypeName := CamelCaseSlice(typeName)
g.P(g.Pkg["proto"]+".RegisterEnum(", strconv.Quote(pkg+ccTypeName), ", ", ccTypeName+"_name, ", ccTypeName+"_value)")
}
func (g *Generator) generateExtensionRegistration(ext *ExtensionDescriptor) {
g.P(g.Pkg["proto"]+".RegisterExtension(", ext.DescName(), ")")
}
// And now lots of helper functions.
// Is c an ASCII lower-case letter?
func isASCIILower(c byte) bool {
return 'a' <= c && c <= 'z'
}
// Is c an ASCII digit?
func isASCIIDigit(c byte) bool {
return '0' <= c && c <= '9'
}
// CamelCase returns the CamelCased name.
// If there is an interior underscore followed by a lower case letter,
// drop the underscore and convert the letter to upper case.
// There is a remote possibility of this rewrite causing a name collision,
// but it's so remote we're prepared to pretend it's nonexistent - since the
// C++ generator lowercases names, it's extremely unlikely to have two fields
// with different capitalizations.
// In short, _my_field_name_2 becomes XMyFieldName2.
func CamelCase(s string) string {
if s == "" {
return ""
}
t := make([]byte, 0, 32)
i := 0
if s[0] == '_' {
// Need a capital letter; drop the '_'.
t = append(t, 'X')
i++
}
// Invariant: if the next letter is lower case, it must be converted
// to upper case.
// That is, we process a word at a time, where words are marked by _ or
// upper case letter. Digits are treated as words.
for ; i < len(s); i++ {
c := s[i]
if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
continue // Skip the underscore in s.
}
if isASCIIDigit(c) {
t = append(t, c)
continue
}
// Assume we have a letter now - if not, it's a bogus identifier.
// The next word is a sequence of characters that must start upper case.
if isASCIILower(c) {
c ^= ' ' // Make it a capital letter.
}
t = append(t, c) // Guaranteed not lower case.
// Accept lower case sequence that follows.
for i+1 < len(s) && isASCIILower(s[i+1]) {
i++
t = append(t, s[i])
}
}
return string(t)
}
// CamelCaseSlice is like CamelCase, but the argument is a slice of strings to
// be joined with "_".
func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) }
// dottedSlice turns a sliced name into a dotted name.
func dottedSlice(elem []string) string { return strings.Join(elem, ".") }
// Given a .proto file name, return the output name for the generated Go program.
func goFileName(name string) string {
ext := path.Ext(name)
if ext == ".proto" || ext == ".protodevel" {
name = name[0 : len(name)-len(ext)]
}
return name + ".pb.go"
}
// Is this field optional?
func isOptional(field *descriptor.FieldDescriptorProto) bool {
return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL
}
// Is this field required?
func isRequired(field *descriptor.FieldDescriptorProto) bool {
return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED
}
// Is this field repeated?
func isRepeated(field *descriptor.FieldDescriptorProto) bool {
return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED
}
// badToUnderscore is the mapping function used to generate Go names from package names,
// which can be dotted in the input .proto file. It replaces non-identifier characters such as
// dot or dash with underscore.
func badToUnderscore(r rune) rune {
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
return r
}
return '_'
}
// baseName returns the last path element of the name, with the last dotted suffix removed.
func baseName(name string) string {
// First, find the last element
if i := strings.LastIndex(name, "/"); i >= 0 {
name = name[i+1:]
}
// Now drop the suffix
if i := strings.LastIndex(name, "."); i >= 0 {
name = name[0:i]
}
return name
}
// The SourceCodeInfo message describes the location of elements of a parsed
// .proto file by way of a "path", which is a sequence of integers that
// describe the route from a FileDescriptorProto to the relevant submessage.
// The path alternates between a field number of a repeated field, and an index
// into that repeated field. The constants below define the field numbers that
// are used.
//
// See descriptor.proto for more information about this.
const (
// tag numbers in FileDescriptorProto
messagePath = 4 // message_type
enumPath = 5 // enum_type
// tag numbers in DescriptorProto
messageFieldPath = 2 // field
messageMessagePath = 3 // nested_type
messageEnumPath = 4 // enum_type
// tag numbers in EnumDescriptorProto
enumValuePath = 2 // value
)
| 1067282423-goproto000 | protoc-gen-go/generator/generator.go | Go | bsd | 59,962 |
# Go support for Protocol Buffers - Google's data interchange format
#
# Copyright 2010 The Go Authors. All rights reserved.
# http://code.google.com/p/goprotobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Not stored here, but plugin.proto is in http://code.google.com/p/protobuf
# at protobuf-2.5.0/src/google/protobuf/compiler/plugin.proto
# Also we need to fix an import.
regenerate:
echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION
cd $(HOME)/src/protobuf-2.5.0/src && \
protoc --go_out=. ./google/protobuf/compiler/plugin.proto && \
cat ./google/protobuf/compiler/plugin.pb.go | \
sed '/^import/s;google/protobuf/descriptor.pb;code.google.com/p/goprotobuf/protoc-gen-go/descriptor;' > $(GOPATH)/src/code.google.com/p/goprotobuf/protoc-gen-go/plugin/plugin.pb.go
restore:
cp plugin.pb.golden plugin.pb.go
preserve:
cp plugin.pb.go plugin.pb.golden
| 1067282423-goproto000 | protoc-gen-go/plugin/Makefile | Makefile | bsd | 2,318 |
# Go support for Protocol Buffers - Google's data interchange format
#
# Copyright 2010 The Go Authors. All rights reserved.
# http://code.google.com/p/goprotobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Not stored here, but descriptor.proto is in http://code.google.com/p/protobuf
# at protobuf-2.5.0/src/google/protobuf/descriptor.proto
regenerate:
echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION
cd $(HOME)/src/protobuf-2.5.0/src && \
protoc --go_out=. ./google/protobuf/descriptor.proto && \
cp ./google/protobuf/descriptor.pb.go $(GOPATH)/src/code.google.com/p/goprotobuf/protoc-gen-go/descriptor/descriptor.pb.go
restore:
cp descriptor.pb.golden descriptor.pb.go
preserve:
cp descriptor.pb.go descriptor.pb.golden
| 1067282423-goproto000 | protoc-gen-go/descriptor/Makefile | Makefile | bsd | 2,187 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
A plugin for the Google protocol buffer compiler to generate Go code.
Run it by building this program and putting it in your path with the name
protoc-gen-go
That word 'go' at the end becomes part of the option string set for the
protocol compiler, so once the protocol compiler (protoc) is installed
you can run
protoc --go_out=output_directory input_directory/file.proto
to generate Go bindings for the protocol defined by file.proto.
With that input, the output will be written to
output_directory/file.pb.go
The generated code is documented in the package comment for
the library.
See the README and documentation for protocol buffers to learn more:
http://code.google.com/p/protobuf/
*/
package documentation
| 1067282423-goproto000 | protoc-gen-go/doc.go | Go | bsd | 2,409 |
# Go support for Protocol Buffers - Google's data interchange format
#
# Copyright 2010 The Go Authors. All rights reserved.
# http://code.google.com/p/goprotobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
install:
go install
test: install generate-test-pbs
go test
generate-test-pbs:
make install && cd testdata && make
| 1067282423-goproto000 | proto/Makefile | Makefile | bsd | 1,762 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
// Functions for parsing the Text protocol buffer format.
// TODO: message sets.
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"unicode/utf8"
)
type ParseError struct {
Message string
Line int // 1-based line number
Offset int // 0-based byte offset from start of input
}
func (p *ParseError) Error() string {
if p.Line == 1 {
// show offset only for first line
return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
}
return fmt.Sprintf("line %d: %v", p.Line, p.Message)
}
type token struct {
value string
err *ParseError
line int // line number
offset int // byte number from start of input, not start of line
unquoted string // the unquoted version of value, if it was a quoted string
}
func (t *token) String() string {
if t.err == nil {
return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
}
return fmt.Sprintf("parse error: %v", t.err)
}
type textParser struct {
s string // remaining input
done bool // whether the parsing is finished (success or error)
backed bool // whether back() was called
offset, line int
cur token
}
func newTextParser(s string) *textParser {
p := new(textParser)
p.s = s
p.line = 1
p.cur.line = 1
return p
}
func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
p.cur.err = pe
p.done = true
return pe
}
// Numbers and identifiers are matched by [-+._A-Za-z0-9]
func isIdentOrNumberChar(c byte) bool {
switch {
case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
return true
case '0' <= c && c <= '9':
return true
}
switch c {
case '-', '+', '.', '_':
return true
}
return false
}
func isWhitespace(c byte) bool {
switch c {
case ' ', '\t', '\n', '\r':
return true
}
return false
}
func (p *textParser) skipWhitespace() {
i := 0
for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
if p.s[i] == '#' {
// comment; skip to end of line or input
for i < len(p.s) && p.s[i] != '\n' {
i++
}
if i == len(p.s) {
break
}
}
if p.s[i] == '\n' {
p.line++
}
i++
}
p.offset += i
p.s = p.s[i:len(p.s)]
if len(p.s) == 0 {
p.done = true
}
}
func (p *textParser) advance() {
// Skip whitespace
p.skipWhitespace()
if p.done {
return
}
// Start of non-whitespace
p.cur.err = nil
p.cur.offset, p.cur.line = p.offset, p.line
p.cur.unquoted = ""
switch p.s[0] {
case '<', '>', '{', '}', ':', '[', ']', ';', ',':
// Single symbol
p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
case '"', '\'':
// Quoted string
i := 1
for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
if p.s[i] == '\\' && i+1 < len(p.s) {
// skip escaped char
i++
}
i++
}
if i >= len(p.s) || p.s[i] != p.s[0] {
p.errorf("unmatched quote")
return
}
unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
if err != nil {
p.errorf("invalid quoted string %v", p.s[0:i+1])
return
}
p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
p.cur.unquoted = unq
default:
i := 0
for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
i++
}
if i == 0 {
p.errorf("unexpected byte %#x", p.s[0])
return
}
p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
}
p.offset += len(p.cur.value)
}
var (
errBadUTF8 = errors.New("bad UTF-8")
errBadHex = errors.New("bad hexadecimal")
)
func unquoteC(s string, quote rune) (string, error) {
// This is based on C++'s tokenizer.cc.
// Despite its name, this is *not* parsing C syntax.
// For instance, "\0" is an invalid quoted string.
// Avoid allocation in trivial cases.
simple := true
for _, r := range s {
if r == '\\' || r == quote {
simple = false
break
}
}
if simple {
return s, nil
}
buf := make([]byte, 0, 3*len(s)/2)
for len(s) > 0 {
r, n := utf8.DecodeRuneInString(s)
if r == utf8.RuneError && n == 1 {
return "", errBadUTF8
}
s = s[n:]
if r != '\\' {
if r < utf8.RuneSelf {
buf = append(buf, byte(r))
} else {
buf = append(buf, string(r)...)
}
continue
}
ch, tail, err := unescape(s)
if err != nil {
return "", err
}
buf = append(buf, ch...)
s = tail
}
return string(buf), nil
}
func unescape(s string) (ch string, tail string, err error) {
r, n := utf8.DecodeRuneInString(s)
if r == utf8.RuneError && n == 1 {
return "", "", errBadUTF8
}
s = s[n:]
switch r {
case 'a':
return "\a", s, nil
case 'b':
return "\b", s, nil
case 'f':
return "\f", s, nil
case 'n':
return "\n", s, nil
case 'r':
return "\r", s, nil
case 't':
return "\t", s, nil
case 'v':
return "\v", s, nil
case '?':
return "?", s, nil // trigraph workaround
case '\'', '"', '\\':
return string(r), s, nil
case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X':
if len(s) < 2 {
return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
}
base := 8
ss := s[:2]
s = s[2:]
if r == 'x' || r == 'X' {
base = 16
} else {
ss = string(r) + ss
}
i, err := strconv.ParseUint(ss, base, 8)
if err != nil {
return "", "", err
}
return string([]byte{byte(i)}), s, nil
case 'u', 'U':
n := 4
if r == 'U' {
n = 8
}
if len(s) < n {
return "", "", fmt.Errorf(`\%c requires %d digits`, r, n)
}
bs := make([]byte, n/2)
for i := 0; i < n; i += 2 {
a, ok1 := unhex(s[i])
b, ok2 := unhex(s[i+1])
if !ok1 || !ok2 {
return "", "", errBadHex
}
bs[i/2] = a<<4 | b
}
s = s[n:]
return string(bs), s, nil
}
return "", "", fmt.Errorf(`unknown escape \%c`, r)
}
// Adapted from src/pkg/strconv/quote.go.
func unhex(b byte) (v byte, ok bool) {
switch {
case '0' <= b && b <= '9':
return b - '0', true
case 'a' <= b && b <= 'f':
return b - 'a' + 10, true
case 'A' <= b && b <= 'F':
return b - 'A' + 10, true
}
return 0, false
}
// Back off the parser by one token. Can only be done between calls to next().
// It makes the next advance() a no-op.
func (p *textParser) back() { p.backed = true }
// Advances the parser and returns the new current token.
func (p *textParser) next() *token {
if p.backed || p.done {
p.backed = false
return &p.cur
}
p.advance()
if p.done {
p.cur.value = ""
} else if len(p.cur.value) > 0 && p.cur.value[0] == '"' {
// Look for multiple quoted strings separated by whitespace,
// and concatenate them.
cat := p.cur
for {
p.skipWhitespace()
if p.done || p.s[0] != '"' {
break
}
p.advance()
if p.cur.err != nil {
return &p.cur
}
cat.value += " " + p.cur.value
cat.unquoted += p.cur.unquoted
}
p.done = false // parser may have seen EOF, but we want to return cat
p.cur = cat
}
return &p.cur
}
// Return an error indicating which required field was not set.
func (p *textParser) missingRequiredFieldError(sv reflect.Value) *ParseError {
st := sv.Type()
sprops := GetProperties(st)
for i := 0; i < st.NumField(); i++ {
if !isNil(sv.Field(i)) {
continue
}
props := sprops.Prop[i]
if props.Required {
return p.errorf("message %v missing required field %q", st, props.OrigName)
}
}
return p.errorf("message %v missing required field", st) // should not happen
}
// Returns the index in the struct for the named field, as well as the parsed tag properties.
func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) {
sprops := GetProperties(st)
i, ok := sprops.decoderOrigNames[name]
if ok {
return i, sprops.Prop[i], true
}
return -1, nil, false
}
// Consume a ':' from the input stream (if the next token is a colon),
// returning an error if a colon is needed but not present.
func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
tok := p.next()
if tok.err != nil {
return tok.err
}
if tok.value != ":" {
// Colon is optional when the field is a group or message.
needColon := true
switch props.Wire {
case "group":
needColon = false
case "bytes":
// A "bytes" field is either a message, a string, or a repeated field;
// those three become *T, *string and []T respectively, so we can check for
// this field being a pointer to a non-string.
if typ.Kind() == reflect.Ptr {
// *T or *string
if typ.Elem().Kind() == reflect.String {
break
}
} else if typ.Kind() == reflect.Slice {
// []T or []*T
if typ.Elem().Kind() != reflect.Ptr {
break
}
}
needColon = false
}
if needColon {
return p.errorf("expected ':', found %q", tok.value)
}
p.back()
}
return nil
}
func (p *textParser) readStruct(sv reflect.Value, terminator string) *ParseError {
st := sv.Type()
reqCount := GetProperties(st).reqCount
// A struct is a sequence of "name: value", terminated by one of
// '>' or '}', or the end of the input. A name may also be
// "[extension]".
for {
tok := p.next()
if tok.err != nil {
return tok.err
}
if tok.value == terminator {
break
}
if tok.value == "[" {
// Looks like an extension.
//
// TODO: Check whether we need to handle
// namespace rooted names (e.g. ".something.Foo").
tok = p.next()
if tok.err != nil {
return tok.err
}
var desc *ExtensionDesc
// This could be faster, but it's functional.
// TODO: Do something smarter than a linear scan.
for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
if d.Name == tok.value {
desc = d
break
}
}
if desc == nil {
return p.errorf("unrecognized extension %q", tok.value)
}
// Check the extension terminator.
tok = p.next()
if tok.err != nil {
return tok.err
}
if tok.value != "]" {
return p.errorf("unrecognized extension terminator %q", tok.value)
}
props := &Properties{}
props.Parse(desc.Tag)
typ := reflect.TypeOf(desc.ExtensionType)
if err := p.checkForColon(props, typ); err != nil {
return err
}
rep := desc.repeated()
// Read the extension structure, and set it in
// the value we're constructing.
var ext reflect.Value
if !rep {
ext = reflect.New(typ).Elem()
} else {
ext = reflect.New(typ.Elem()).Elem()
}
if err := p.readAny(ext, props); err != nil {
return err
}
ep := sv.Addr().Interface().(extendableProto)
if !rep {
SetExtension(ep, desc, ext.Interface())
} else {
old, err := GetExtension(ep, desc)
var sl reflect.Value
if err == nil {
sl = reflect.ValueOf(old) // existing slice
} else {
sl = reflect.MakeSlice(typ, 0, 1)
}
sl = reflect.Append(sl, ext)
SetExtension(ep, desc, sl.Interface())
}
} else {
// This is a normal, non-extension field.
fi, props, ok := structFieldByName(st, tok.value)
if !ok {
return p.errorf("unknown field name %q in %v", tok.value, st)
}
dst := sv.Field(fi)
isDstNil := isNil(dst)
// Check that it's not already set if it's not a repeated field.
if !props.Repeated && !isDstNil {
return p.errorf("non-repeated field %q was repeated", tok.value)
}
if err := p.checkForColon(props, st.Field(fi).Type); err != nil {
return err
}
// Parse into the field.
if err := p.readAny(dst, props); err != nil {
return err
}
if props.Required {
reqCount--
}
}
// For backward compatibility, permit a semicolon or comma after a field.
tok = p.next()
if tok.err != nil {
return tok.err
}
if tok.value != ";" && tok.value != "," {
p.back()
}
}
if reqCount > 0 {
return p.missingRequiredFieldError(sv)
}
return nil
}
func (p *textParser) readAny(v reflect.Value, props *Properties) *ParseError {
tok := p.next()
if tok.err != nil {
return tok.err
}
if tok.value == "" {
return p.errorf("unexpected EOF")
}
switch fv := v; fv.Kind() {
case reflect.Slice:
at := v.Type()
if at.Elem().Kind() == reflect.Uint8 {
// Special case for []byte
if tok.value[0] != '"' && tok.value[0] != '\'' {
// Deliberately written out here, as the error after
// this switch statement would write "invalid []byte: ...",
// which is not as user-friendly.
return p.errorf("invalid string: %v", tok.value)
}
bytes := []byte(tok.unquoted)
fv.Set(reflect.ValueOf(bytes))
return nil
}
// Repeated field. May already exist.
flen := fv.Len()
if flen == fv.Cap() {
nav := reflect.MakeSlice(at, flen, 2*flen+1)
reflect.Copy(nav, fv)
fv.Set(nav)
}
fv.SetLen(flen + 1)
// Read one.
p.back()
return p.readAny(fv.Index(flen), props)
case reflect.Bool:
// Either "true", "false", 1 or 0.
switch tok.value {
case "true", "1":
fv.SetBool(true)
return nil
case "false", "0":
fv.SetBool(false)
return nil
}
case reflect.Float32, reflect.Float64:
v := tok.value
// Ignore 'f' for compatibility with output generated by C++, but don't
// remove 'f' when the value is "-inf" or "inf".
if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
v = v[:len(v)-1]
}
if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
fv.SetFloat(f)
return nil
}
case reflect.Int32:
if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
fv.SetInt(x)
return nil
}
if len(props.Enum) == 0 {
break
}
m, ok := enumValueMaps[props.Enum]
if !ok {
break
}
x, ok := m[tok.value]
if !ok {
break
}
fv.SetInt(int64(x))
return nil
case reflect.Int64:
if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
fv.SetInt(x)
return nil
}
case reflect.Ptr:
// A basic field (indirected through pointer), or a repeated message/group
p.back()
fv.Set(reflect.New(fv.Type().Elem()))
return p.readAny(fv.Elem(), props)
case reflect.String:
if tok.value[0] == '"' || tok.value[0] == '\'' {
fv.SetString(tok.unquoted)
return nil
}
case reflect.Struct:
var terminator string
switch tok.value {
case "{":
terminator = "}"
case "<":
terminator = ">"
default:
return p.errorf("expected '{' or '<', found %q", tok.value)
}
return p.readStruct(fv, terminator)
case reflect.Uint32:
if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
fv.SetUint(uint64(x))
return nil
}
case reflect.Uint64:
if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
fv.SetUint(x)
return nil
}
}
return p.errorf("invalid %v: %v", v.Type(), tok.value)
}
// UnmarshalText reads a protocol buffer in Text format.
func UnmarshalText(s string, pb Message) error {
v := reflect.ValueOf(pb)
if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
return pe
}
return nil
}
| 1067282423-goproto000 | proto/text_parser.go | Go | bsd | 16,293 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2011 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Protocol buffer deep copy.
// TODO: MessageSet and RawMessage.
package proto
import (
"log"
"reflect"
"strings"
)
// Clone returns a deep copy of a protocol buffer.
func Clone(pb Message) Message {
in := reflect.ValueOf(pb)
if in.IsNil() {
return pb
}
out := reflect.New(in.Type().Elem())
// out is empty so a merge is a deep copy.
mergeStruct(out.Elem(), in.Elem())
return out.Interface().(Message)
}
// Merge merges src into dst.
// Required and optional fields that are set in src will be set to that value in dst.
// Elements of repeated fields will be appended.
// Merge panics if src and dst are not the same type, or if dst is nil.
func Merge(dst, src Message) {
in := reflect.ValueOf(src)
out := reflect.ValueOf(dst)
if out.IsNil() {
panic("proto: nil destination")
}
if in.Type() != out.Type() {
// Explicit test prior to mergeStruct so that mistyped nils will fail
panic("proto: type mismatch")
}
if in.IsNil() {
// Merging nil into non-nil is a quiet no-op
return
}
mergeStruct(out.Elem(), in.Elem())
}
func mergeStruct(out, in reflect.Value) {
for i := 0; i < in.NumField(); i++ {
f := in.Type().Field(i)
if strings.HasPrefix(f.Name, "XXX_") {
continue
}
mergeAny(out.Field(i), in.Field(i))
}
if emIn, ok := in.Addr().Interface().(extendableProto); ok {
emOut := out.Addr().Interface().(extendableProto)
mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap())
}
uf := in.FieldByName("XXX_unrecognized")
if !uf.IsValid() {
return
}
uin := uf.Bytes()
if len(uin) > 0 {
out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
}
}
func mergeAny(out, in reflect.Value) {
if in.Type() == protoMessageType {
if !in.IsNil() {
if out.IsNil() {
out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
} else {
Merge(out.Interface().(Message), in.Interface().(Message))
}
}
return
}
switch in.Kind() {
case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
reflect.String, reflect.Uint32, reflect.Uint64:
out.Set(in)
case reflect.Ptr:
if in.IsNil() {
return
}
if out.IsNil() {
out.Set(reflect.New(in.Elem().Type()))
}
mergeAny(out.Elem(), in.Elem())
case reflect.Slice:
if in.IsNil() {
return
}
n := in.Len()
if out.IsNil() {
out.Set(reflect.MakeSlice(in.Type(), 0, n))
}
switch in.Type().Elem().Kind() {
case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
reflect.String, reflect.Uint32, reflect.Uint64, reflect.Uint8:
out.Set(reflect.AppendSlice(out, in))
default:
for i := 0; i < n; i++ {
x := reflect.Indirect(reflect.New(in.Type().Elem()))
mergeAny(x, in.Index(i))
out.Set(reflect.Append(out, x))
}
}
case reflect.Struct:
mergeStruct(out, in)
default:
// unknown type, so not a protocol buffer
log.Printf("proto: don't know how to copy %v", in)
}
}
func mergeExtension(out, in map[int32]Extension) {
for extNum, eIn := range in {
eOut := Extension{desc: eIn.desc}
if eIn.value != nil {
v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
mergeAny(v, reflect.ValueOf(eIn.value))
eOut.value = v.Interface()
}
if eIn.enc != nil {
eOut.enc = make([]byte, len(eIn.enc))
copy(eOut.enc, eIn.enc)
}
out[extNum] = eOut
}
}
| 1067282423-goproto000 | proto/clone.go | Go | bsd | 4,980 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2011 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Protocol buffer comparison.
// TODO: MessageSet.
package proto
import (
"bytes"
"log"
"reflect"
"strings"
)
/*
Equal returns true iff protocol buffers a and b are equal.
The arguments must both be pointers to protocol buffer structs.
Equality is defined in this way:
- Two messages are equal iff they are the same type,
corresponding fields are equal, unknown field sets
are equal, and extensions sets are equal.
- Two set scalar fields are equal iff their values are equal.
If the fields are of a floating-point type, remember that
NaN != x for all x, including NaN.
- Two repeated fields are equal iff their lengths are the same,
and their corresponding elements are equal (a "bytes" field,
although represented by []byte, is not a repeated field)
- Two unset fields are equal.
- Two unknown field sets are equal if their current
encoded state is equal. (TODO)
- Two extension sets are equal iff they have corresponding
elements that are pairwise equal.
- Every other combination of things are not equal.
The return value is undefined if a and b are not protocol buffers.
*/
func Equal(a, b Message) bool {
if a == nil || b == nil {
return a == b
}
v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b)
if v1.Type() != v2.Type() {
return false
}
if v1.Kind() == reflect.Ptr {
if v1.IsNil() {
return v2.IsNil()
}
if v2.IsNil() {
return false
}
v1, v2 = v1.Elem(), v2.Elem()
}
if v1.Kind() != reflect.Struct {
return false
}
return equalStruct(v1, v2)
}
// v1 and v2 are known to have the same type.
func equalStruct(v1, v2 reflect.Value) bool {
for i := 0; i < v1.NumField(); i++ {
f := v1.Type().Field(i)
if strings.HasPrefix(f.Name, "XXX_") {
continue
}
f1, f2 := v1.Field(i), v2.Field(i)
if f.Type.Kind() == reflect.Ptr {
if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 {
// both unset
continue
} else if n1 != n2 {
// set/unset mismatch
return false
}
b1, ok := f1.Interface().(raw)
if ok {
b2 := f2.Interface().(raw)
// RawMessage
if !bytes.Equal(b1.Bytes(), b2.Bytes()) {
return false
}
continue
}
f1, f2 = f1.Elem(), f2.Elem()
}
if !equalAny(f1, f2) {
return false
}
}
if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() {
em2 := v2.FieldByName("XXX_extensions")
if !equalExtensions(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) {
return false
}
}
uf := v1.FieldByName("XXX_unrecognized")
if !uf.IsValid() {
return true
}
u1 := uf.Bytes()
u2 := v2.FieldByName("XXX_unrecognized").Bytes()
if !bytes.Equal(u1, u2) {
return false
}
return true
}
// v1 and v2 are known to have the same type.
func equalAny(v1, v2 reflect.Value) bool {
if v1.Type() == protoMessageType {
m1, _ := v1.Interface().(Message)
m2, _ := v2.Interface().(Message)
return Equal(m1, m2)
}
switch v1.Kind() {
case reflect.Bool:
return v1.Bool() == v2.Bool()
case reflect.Float32, reflect.Float64:
return v1.Float() == v2.Float()
case reflect.Int32, reflect.Int64:
return v1.Int() == v2.Int()
case reflect.Ptr:
return equalAny(v1.Elem(), v2.Elem())
case reflect.Slice:
if v1.Type().Elem().Kind() == reflect.Uint8 {
// short circuit: []byte
if v1.IsNil() != v2.IsNil() {
return false
}
return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
}
if v1.Len() != v2.Len() {
return false
}
for i := 0; i < v1.Len(); i++ {
if !equalAny(v1.Index(i), v2.Index(i)) {
return false
}
}
return true
case reflect.String:
return v1.Interface().(string) == v2.Interface().(string)
case reflect.Struct:
return equalStruct(v1, v2)
case reflect.Uint32, reflect.Uint64:
return v1.Uint() == v2.Uint()
}
// unknown type, so not a protocol buffer
log.Printf("proto: don't know how to compare %v", v1)
return false
}
// base is the struct type that the extensions are based on.
// em1 and em2 are extension maps.
func equalExtensions(base reflect.Type, em1, em2 map[int32]Extension) bool {
if len(em1) != len(em2) {
return false
}
for extNum, e1 := range em1 {
e2, ok := em2[extNum]
if !ok {
return false
}
m1, m2 := e1.value, e2.value
if m1 != nil && m2 != nil {
// Both are unencoded.
if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2)) {
return false
}
continue
}
// At least one is encoded. To do a semantically correct comparison
// we need to unmarshal them first.
var desc *ExtensionDesc
if m := extensionMaps[base]; m != nil {
desc = m[extNum]
}
if desc == nil {
log.Printf("proto: don't know how to compare extension %d of %v", extNum, base)
continue
}
var err error
if m1 == nil {
m1, err = decodeExtension(e1.enc, desc)
}
if m2 == nil && err == nil {
m2, err = decodeExtension(e2.enc, desc)
}
if err != nil {
// The encoded form is invalid.
log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err)
return false
}
if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2)) {
return false
}
}
return true
}
| 1067282423-goproto000 | proto/equal.go | Go | bsd | 6,800 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2012 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// +build !appengine
// This file contains the implementation of the proto field accesses using package unsafe.
package proto
import (
"reflect"
"unsafe"
)
// NOTE: These type_Foo functions would more idiomatically be methods,
// but Go does not allow methods on pointer types, and we must preserve
// some pointer type for the garbage collector. We use these
// funcs with clunky names as our poor approximation to methods.
//
// An alternative would be
// type structPointer struct { p unsafe.Pointer }
// but that does not registerize as well.
// A structPointer is a pointer to a struct.
type structPointer unsafe.Pointer
// toStructPointer returns a structPointer equivalent to the given reflect value.
func toStructPointer(v reflect.Value) structPointer {
return structPointer(unsafe.Pointer(v.Pointer()))
}
// IsNil reports whether p is nil.
func structPointer_IsNil(p structPointer) bool {
return p == nil
}
// Interface returns the struct pointer, assumed to have element type t,
// as an interface value.
func structPointer_Interface(p structPointer, t reflect.Type) interface{} {
return reflect.NewAt(t, unsafe.Pointer(p)).Interface()
}
// A field identifies a field in a struct, accessible from a structPointer.
// In this implementation, a field is identified by its byte offset from the start of the struct.
type field uintptr
// toField returns a field equivalent to the given reflect field.
func toField(f *reflect.StructField) field {
return field(f.Offset)
}
// invalidField is an invalid field identifier.
const invalidField = ^field(0)
// IsValid reports whether the field identifier is valid.
func (f field) IsValid() bool {
return f != ^field(0)
}
// Bytes returns the address of a []byte field in the struct.
func structPointer_Bytes(p structPointer, f field) *[]byte {
return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// BytesSlice returns the address of a [][]byte field in the struct.
func structPointer_BytesSlice(p structPointer, f field) *[][]byte {
return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// Bool returns the address of a *bool field in the struct.
func structPointer_Bool(p structPointer, f field) **bool {
return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// BoolSlice returns the address of a []bool field in the struct.
func structPointer_BoolSlice(p structPointer, f field) *[]bool {
return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// String returns the address of a *string field in the struct.
func structPointer_String(p structPointer, f field) **string {
return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// StringSlice returns the address of a []string field in the struct.
func structPointer_StringSlice(p structPointer, f field) *[]string {
return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// ExtMap returns the address of an extension map field in the struct.
func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// SetStructPointer writes a *struct field in the struct.
func structPointer_SetStructPointer(p structPointer, f field, q structPointer) {
*(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q
}
// GetStructPointer reads a *struct field in the struct.
func structPointer_GetStructPointer(p structPointer, f field) structPointer {
return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// StructPointerSlice the address of a []*struct field in the struct.
func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice {
return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups).
type structPointerSlice []structPointer
func (v *structPointerSlice) Len() int { return len(*v) }
func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] }
func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) }
// A word32 is the address of a "pointer to 32-bit value" field.
type word32 **uint32
// IsNil reports whether *v is nil.
func word32_IsNil(p word32) bool {
return *p == nil
}
// Set sets *v to point at a newly allocated word set to x.
func word32_Set(p word32, o *Buffer, x uint32) {
if len(o.uint32s) == 0 {
o.uint32s = make([]uint32, uint32PoolSize)
}
o.uint32s[0] = x
*p = &o.uint32s[0]
o.uint32s = o.uint32s[1:]
}
// Get gets the value pointed at by *v.
func word32_Get(p word32) uint32 {
return **p
}
// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct.
func structPointer_Word32(p structPointer, f field) word32 {
return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f))))
}
// A word32Slice is a slice of 32-bit values.
type word32Slice []uint32
func (v *word32Slice) Append(x uint32) { *v = append(*v, x) }
func (v *word32Slice) Len() int { return len(*v) }
func (v *word32Slice) Index(i int) uint32 { return (*v)[i] }
// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct.
func structPointer_Word32Slice(p structPointer, f field) *word32Slice {
return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// word64 is like word32 but for 64-bit values.
type word64 **uint64
func word64_Set(p word64, o *Buffer, x uint64) {
if len(o.uint64s) == 0 {
o.uint64s = make([]uint64, uint64PoolSize)
}
o.uint64s[0] = x
*p = &o.uint64s[0]
o.uint64s = o.uint64s[1:]
}
func word64_IsNil(p word64) bool {
return *p == nil
}
func word64_Get(p word64) uint64 {
return **p
}
func structPointer_Word64(p structPointer, f field) word64 {
return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f))))
}
// word64Slice is like word32Slice but for 64-bit values.
type word64Slice []uint64
func (v *word64Slice) Append(x uint64) { *v = append(*v, x) }
func (v *word64Slice) Len() int { return len(*v) }
func (v *word64Slice) Index(i int) uint64 { return (*v)[i] }
func structPointer_Word64Slice(p structPointer, f field) *word64Slice {
return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
| 1067282423-goproto000 | proto/pointer_unsafe.go | Go | bsd | 7,903 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2012 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Functions to determine the size of an encoded protocol buffer.
package proto
import (
"log"
"reflect"
"strings"
)
// Size returns the encoded size of a protocol buffer.
// This function is expensive enough to be avoided unless proven worthwhile with instrumentation.
func Size(pb Message) int {
in := reflect.ValueOf(pb)
if in.IsNil() {
return 0
}
return sizeStruct(in.Elem())
}
func sizeStruct(x reflect.Value) (n int) {
sprop := GetProperties(x.Type())
for _, prop := range sprop.Prop {
if strings.HasPrefix(prop.Name, "XXX_") { // handled below
continue
}
fi, _ := sprop.decoderTags.get(prop.Tag)
f := x.Field(fi)
switch f.Kind() {
case reflect.Ptr:
if f.IsNil() {
continue
}
n += len(prop.tagcode)
f = f.Elem() // avoid a recursion in sizeField
case reflect.Slice:
if f.IsNil() {
continue
}
if f.Len() == 0 && f.Type().Elem().Kind() != reflect.Uint8 {
// short circuit for empty repeated fields.
// []byte isn't a repeated field.
continue
}
default:
log.Printf("proto: unknown struct field type %v", f.Type())
continue
}
n += sizeField(f, prop)
}
if em, ok := x.Addr().Interface().(extendableProto); ok {
for _, ext := range em.ExtensionMap() {
ms := len(ext.enc)
if ext.enc == nil {
props := new(Properties)
props.Init(reflect.TypeOf(ext.desc.ExtensionType), "x", ext.desc.Tag, nil)
ms = len(props.tagcode) + sizeField(reflect.ValueOf(ext.value), props)
}
n += ms
}
}
if uf := x.FieldByName("XXX_unrecognized"); uf.IsValid() {
n += uf.Len()
}
return n
}
func sizeField(x reflect.Value, prop *Properties) (n int) {
if x.Type().Kind() == reflect.Slice {
n := x.Len()
et := x.Type().Elem()
if et.Kind() == reflect.Uint8 {
// []byte is easy.
return len(prop.tagcode) + sizeVarint(uint64(n)) + n
}
var nb int
// []bool and repeated fixed integer types are easy.
switch {
case et.Kind() == reflect.Bool:
nb += n
case prop.WireType == WireFixed64:
nb += n * 8
case prop.WireType == WireFixed32:
nb += n * 4
default:
for i := 0; i < n; i++ {
nb += sizeField(x.Index(i), prop)
}
}
// Non-packed repeated fields have a per-element header of the tagcode.
// Packed repeated fields only have a single header: the tag code plus a varint of the number of bytes.
if !prop.Packed {
nb += len(prop.tagcode) * n
} else {
nb += len(prop.tagcode) + sizeVarint(uint64(nb))
}
return nb
}
// easy scalars
switch prop.WireType {
case WireFixed64:
return 8
case WireFixed32:
return 4
}
switch x.Kind() {
case reflect.Bool:
return 1
case reflect.Int32, reflect.Int64:
if prop.Wire == "varint" {
return sizeVarint(uint64(x.Int()))
} else if prop.Wire == "zigzag32" || prop.Wire == "zigzag64" {
return sizeZigZag(uint64(x.Int()))
}
case reflect.Ptr:
return sizeField(x.Elem(), prop)
case reflect.String:
n := x.Len()
return sizeVarint(uint64(n)) + n
case reflect.Struct:
nb := sizeStruct(x)
if prop.Wire == "group" {
// Groups have start and end tags instead of a start tag and a length.
return nb + len(prop.tagcode)
}
return sizeVarint(uint64(nb)) + nb
case reflect.Uint32, reflect.Uint64:
if prop.Wire == "varint" {
return sizeVarint(uint64(x.Uint()))
} else if prop.Wire == "zigzag32" || prop.Wire == "zigzag64" {
return sizeZigZag(uint64(x.Int()))
}
default:
log.Printf("proto.sizeField: unhandled kind %v", x.Kind())
}
// unknown type, so not a protocol buffer
log.Printf("proto: don't know size of %v", x.Type())
return 0
}
func sizeVarint(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sizeZigZag(x uint64) (n int) {
return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
| 1067282423-goproto000 | proto/size.go | Go | bsd | 5,458 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
/*
* Support for message sets.
*/
import (
"errors"
"reflect"
"sort"
)
// ErrNoMessageTypeId occurs when a protocol buffer does not have a message type ID.
// A message type ID is required for storing a protocol buffer in a message set.
var ErrNoMessageTypeId = errors.New("proto does not have a message type ID")
// The first two types (_MessageSet_Item and MessageSet)
// model what the protocol compiler produces for the following protocol message:
// message MessageSet {
// repeated group Item = 1 {
// required int32 type_id = 2;
// required string message = 3;
// };
// }
// That is the MessageSet wire format. We can't use a proto to generate these
// because that would introduce a circular dependency between it and this package.
//
// When a proto1 proto has a field that looks like:
// optional message<MessageSet> info = 3;
// the protocol compiler produces a field in the generated struct that looks like:
// Info *_proto_.MessageSet `protobuf:"bytes,3,opt,name=info"`
// The package is automatically inserted so there is no need for that proto file to
// import this package.
type _MessageSet_Item struct {
TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
Message []byte `protobuf:"bytes,3,req,name=message"`
}
type MessageSet struct {
Item []*_MessageSet_Item `protobuf:"group,1,rep"`
XXX_unrecognized []byte
// TODO: caching?
}
// Make sure MessageSet is a Message.
var _ Message = (*MessageSet)(nil)
// messageTypeIder is an interface satisfied by a protocol buffer type
// that may be stored in a MessageSet.
type messageTypeIder interface {
MessageTypeId() int32
}
func (ms *MessageSet) find(pb Message) *_MessageSet_Item {
mti, ok := pb.(messageTypeIder)
if !ok {
return nil
}
id := mti.MessageTypeId()
for _, item := range ms.Item {
if *item.TypeId == id {
return item
}
}
return nil
}
func (ms *MessageSet) Has(pb Message) bool {
if ms.find(pb) != nil {
return true
}
return false
}
func (ms *MessageSet) Unmarshal(pb Message) error {
if item := ms.find(pb); item != nil {
return Unmarshal(item.Message, pb)
}
if _, ok := pb.(messageTypeIder); !ok {
return ErrNoMessageTypeId
}
return nil // TODO: return error instead?
}
func (ms *MessageSet) Marshal(pb Message) error {
msg, err := Marshal(pb)
if err != nil {
return err
}
if item := ms.find(pb); item != nil {
// reuse existing item
item.Message = msg
return nil
}
mti, ok := pb.(messageTypeIder)
if !ok {
return ErrWrongType // TODO: custom error?
}
mtid := mti.MessageTypeId()
ms.Item = append(ms.Item, &_MessageSet_Item{
TypeId: &mtid,
Message: msg,
})
return nil
}
func (ms *MessageSet) Reset() { *ms = MessageSet{} }
func (ms *MessageSet) String() string { return CompactTextString(ms) }
func (*MessageSet) ProtoMessage() {}
// Support for the message_set_wire_format message option.
func skipVarint(buf []byte) []byte {
i := 0
for ; buf[i]&0x80 != 0; i++ {
}
return buf[i+1:]
}
// MarshalMessageSet encodes the extension map represented by m in the message set wire format.
// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option.
func MarshalMessageSet(m map[int32]Extension) ([]byte, error) {
if err := encodeExtensionMap(m); err != nil {
return nil, err
}
// Sort extension IDs to provide a deterministic encoding.
// See also enc_map in encode.go.
ids := make([]int, 0, len(m))
for id := range m {
ids = append(ids, int(id))
}
sort.Ints(ids)
ms := &MessageSet{Item: make([]*_MessageSet_Item, 0, len(m))}
for _, id := range ids {
e := m[int32(id)]
// Remove the wire type and field number varint, as well as the length varint.
msg := skipVarint(skipVarint(e.enc))
ms.Item = append(ms.Item, &_MessageSet_Item{
TypeId: Int32(int32(id)),
Message: msg,
})
}
return Marshal(ms)
}
// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
func UnmarshalMessageSet(buf []byte, m map[int32]Extension) error {
ms := new(MessageSet)
if err := Unmarshal(buf, ms); err != nil {
return err
}
for _, item := range ms.Item {
// restore wire type and field number varint, plus length varint.
b := EncodeVarint(uint64(*item.TypeId)<<3 | WireBytes)
b = append(b, EncodeVarint(uint64(len(item.Message)))...)
b = append(b, item.Message...)
m[*item.TypeId] = Extension{enc: b}
}
return nil
}
// A global registry of types that can be used in a MessageSet.
var messageSetMap = make(map[int32]messageSetDesc)
type messageSetDesc struct {
t reflect.Type // pointer to struct
name string
}
// RegisterMessageSetType is called from the generated code.
func RegisterMessageSetType(i messageTypeIder, name string) {
messageSetMap[i.MessageTypeId()] = messageSetDesc{
t: reflect.TypeOf(i),
name: name,
}
}
| 1067282423-goproto000 | proto/message_set.go | Go | bsd | 6,680 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
/*
* Routines for decoding protocol buffer data to construct in-memory representations.
*/
import (
"errors"
"fmt"
"io"
"os"
"reflect"
)
// ErrWrongType occurs when the wire encoding for the field disagrees with
// that specified in the type being decoded. This is usually caused by attempting
// to convert an encoded protocol buffer into a struct of the wrong type.
var ErrWrongType = errors.New("field/encoding mismatch: wrong type for field")
// errOverflow is returned when an integer is too large to be represented.
var errOverflow = errors.New("proto: integer overflow")
// The fundamental decoders that interpret bytes on the wire.
// Those that take integer types all return uint64 and are
// therefore of type valueDecoder.
// DecodeVarint reads a varint-encoded integer from the slice.
// It returns the integer and the number of bytes consumed, or
// zero if there is not enough.
// This is the format for the
// int32, int64, uint32, uint64, bool, and enum
// protocol buffer types.
func DecodeVarint(buf []byte) (x uint64, n int) {
// x, n already 0
for shift := uint(0); shift < 64; shift += 7 {
if n >= len(buf) {
return 0, 0
}
b := uint64(buf[n])
n++
x |= (b & 0x7F) << shift
if (b & 0x80) == 0 {
return x, n
}
}
// The number is too large to represent in a 64-bit value.
return 0, 0
}
// DecodeVarint reads a varint-encoded integer from the Buffer.
// This is the format for the
// int32, int64, uint32, uint64, bool, and enum
// protocol buffer types.
func (p *Buffer) DecodeVarint() (x uint64, err error) {
// x, err already 0
i := p.index
l := len(p.buf)
for shift := uint(0); shift < 64; shift += 7 {
if i >= l {
err = io.ErrUnexpectedEOF
return
}
b := p.buf[i]
i++
x |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
p.index = i
return
}
}
// The number is too large to represent in a 64-bit value.
err = errOverflow
return
}
// DecodeFixed64 reads a 64-bit integer from the Buffer.
// This is the format for the
// fixed64, sfixed64, and double protocol buffer types.
func (p *Buffer) DecodeFixed64() (x uint64, err error) {
// x, err already 0
i := p.index + 8
if i < 0 || i > len(p.buf) {
err = io.ErrUnexpectedEOF
return
}
p.index = i
x = uint64(p.buf[i-8])
x |= uint64(p.buf[i-7]) << 8
x |= uint64(p.buf[i-6]) << 16
x |= uint64(p.buf[i-5]) << 24
x |= uint64(p.buf[i-4]) << 32
x |= uint64(p.buf[i-3]) << 40
x |= uint64(p.buf[i-2]) << 48
x |= uint64(p.buf[i-1]) << 56
return
}
// DecodeFixed32 reads a 32-bit integer from the Buffer.
// This is the format for the
// fixed32, sfixed32, and float protocol buffer types.
func (p *Buffer) DecodeFixed32() (x uint64, err error) {
// x, err already 0
i := p.index + 4
if i < 0 || i > len(p.buf) {
err = io.ErrUnexpectedEOF
return
}
p.index = i
x = uint64(p.buf[i-4])
x |= uint64(p.buf[i-3]) << 8
x |= uint64(p.buf[i-2]) << 16
x |= uint64(p.buf[i-1]) << 24
return
}
// DecodeZigzag64 reads a zigzag-encoded 64-bit integer
// from the Buffer.
// This is the format used for the sint64 protocol buffer type.
func (p *Buffer) DecodeZigzag64() (x uint64, err error) {
x, err = p.DecodeVarint()
if err != nil {
return
}
x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63)
return
}
// DecodeZigzag32 reads a zigzag-encoded 32-bit integer
// from the Buffer.
// This is the format used for the sint32 protocol buffer type.
func (p *Buffer) DecodeZigzag32() (x uint64, err error) {
x, err = p.DecodeVarint()
if err != nil {
return
}
x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31))
return
}
// These are not ValueDecoders: they produce an array of bytes or a string.
// bytes, embedded messages
// DecodeRawBytes reads a count-delimited byte buffer from the Buffer.
// This is the format used for the bytes protocol buffer
// type and for embedded messages.
func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) {
n, err := p.DecodeVarint()
if err != nil {
return
}
nb := int(n)
if nb < 0 {
return nil, fmt.Errorf("proto: bad byte length %d", nb)
}
end := p.index + nb
if end < p.index || end > len(p.buf) {
return nil, io.ErrUnexpectedEOF
}
if !alloc {
// todo: check if can get more uses of alloc=false
buf = p.buf[p.index:end]
p.index += nb
return
}
buf = make([]byte, nb)
copy(buf, p.buf[p.index:])
p.index += nb
return
}
// DecodeStringBytes reads an encoded string from the Buffer.
// This is the format used for the proto2 string type.
func (p *Buffer) DecodeStringBytes() (s string, err error) {
buf, err := p.DecodeRawBytes(false)
if err != nil {
return
}
return string(buf), nil
}
// Skip the next item in the buffer. Its wire type is decoded and presented as an argument.
// If the protocol buffer has extensions, and the field matches, add it as an extension.
// Otherwise, if the XXX_unrecognized field exists, append the skipped data there.
func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error {
oi := o.index
err := o.skip(t, tag, wire)
if err != nil {
return err
}
if !unrecField.IsValid() {
return nil
}
ptr := structPointer_Bytes(base, unrecField)
if *ptr == nil {
// This is the first skipped element,
// allocate a new buffer.
*ptr = o.bufalloc()
}
// Add the skipped field to struct field
obuf := o.buf
o.buf = *ptr
o.EncodeVarint(uint64(tag<<3 | wire))
*ptr = append(o.buf, obuf[oi:o.index]...)
o.buf = obuf
return nil
}
// Skip the next item in the buffer. Its wire type is decoded and presented as an argument.
func (o *Buffer) skip(t reflect.Type, tag, wire int) error {
var u uint64
var err error
switch wire {
case WireVarint:
_, err = o.DecodeVarint()
case WireFixed64:
_, err = o.DecodeFixed64()
case WireBytes:
_, err = o.DecodeRawBytes(false)
case WireFixed32:
_, err = o.DecodeFixed32()
case WireStartGroup:
for {
u, err = o.DecodeVarint()
if err != nil {
break
}
fwire := int(u & 0x7)
if fwire == WireEndGroup {
break
}
ftag := int(u >> 3)
err = o.skip(t, ftag, fwire)
if err != nil {
break
}
}
default:
err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t)
}
return err
}
// Unmarshaler is the interface representing objects that can
// unmarshal themselves. The method should reset the receiver before
// decoding starts. The argument points to data that may be
// overwritten, so implementations should not keep references to the
// buffer.
type Unmarshaler interface {
Unmarshal([]byte) error
}
// Unmarshal parses the protocol buffer representation in buf and places the
// decoded result in pb. If the struct underlying pb does not match
// the data in buf, the results can be unpredictable.
//
// Unmarshal resets pb before starting to unmarshal, so any
// existing data in pb is always removed. Use UnmarshalMerge
// to preserve and append to existing data.
func Unmarshal(buf []byte, pb Message) error {
pb.Reset()
return UnmarshalMerge(buf, pb)
}
// UnmarshalMerge parses the protocol buffer representation in buf and
// writes the decoded result to pb. If the struct underlying pb does not match
// the data in buf, the results can be unpredictable.
//
// UnmarshalMerge merges into existing data in pb.
// Most code should use Unmarshal instead.
func UnmarshalMerge(buf []byte, pb Message) error {
// If the object can unmarshal itself, let it.
if u, ok := pb.(Unmarshaler); ok {
return u.Unmarshal(buf)
}
return NewBuffer(buf).Unmarshal(pb)
}
// Unmarshal parses the protocol buffer representation in the
// Buffer and places the decoded result in pb. If the struct
// underlying pb does not match the data in the buffer, the results can be
// unpredictable.
func (p *Buffer) Unmarshal(pb Message) error {
// If the object can unmarshal itself, let it.
if u, ok := pb.(Unmarshaler); ok {
err := u.Unmarshal(p.buf[p.index:])
p.index = len(p.buf)
return err
}
typ, base, err := getbase(pb)
if err != nil {
return err
}
err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base)
if collectStats {
stats.Decode++
}
return err
}
// unmarshalType does the work of unmarshaling a structure.
func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error {
required, reqFields := prop.reqCount, uint64(0)
var err error
for err == nil && o.index < len(o.buf) {
oi := o.index
var u uint64
u, err = o.DecodeVarint()
if err != nil {
break
}
wire := int(u & 0x7)
if wire == WireEndGroup {
if is_group {
return nil // input is satisfied
}
return ErrWrongType
}
tag := int(u >> 3)
if tag <= 0 {
return fmt.Errorf("proto: illegal tag %d", tag)
}
fieldnum, ok := prop.decoderTags.get(tag)
if !ok {
// Maybe it's an extension?
if prop.extendable {
if e := structPointer_Interface(base, st).(extendableProto); isExtensionField(e, int32(tag)) {
if err = o.skip(st, tag, wire); err == nil {
ext := e.ExtensionMap()[int32(tag)] // may be missing
ext.enc = append(ext.enc, o.buf[oi:o.index]...)
e.ExtensionMap()[int32(tag)] = ext
}
continue
}
}
err = o.skipAndSave(st, tag, wire, base, prop.unrecField)
continue
}
p := prop.Prop[fieldnum]
if p.dec == nil {
fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name)
continue
}
dec := p.dec
if wire != WireStartGroup && wire != p.WireType {
if wire == WireBytes && p.packedDec != nil {
// a packable field
dec = p.packedDec
} else {
err = ErrWrongType
continue
}
}
err = dec(o, p, base)
if err == nil && p.Required {
// Successfully decoded a required field.
if tag <= 64 {
// use bitmap for fields 1-64 to catch field reuse.
var mask uint64 = 1 << uint64(tag-1)
if reqFields&mask == 0 {
// new required field
reqFields |= mask
required--
}
} else {
// This is imprecise. It can be fooled by a required field
// with a tag > 64 that is encoded twice; that's very rare.
// A fully correct implementation would require allocating
// a data structure, which we would like to avoid.
required--
}
}
}
if err == nil {
if is_group {
return io.ErrUnexpectedEOF
}
if required > 0 {
return &ErrRequiredNotSet{st}
}
}
return err
}
// Individual type decoders
// For each,
// u is the decoded value,
// v is a pointer to the field (pointer) in the struct
// Sizes of the pools to allocate inside the Buffer.
// The goal is modest amortization and allocation
// on at least 16-byte boundaries.
const (
boolPoolSize = 16
uint32PoolSize = 8
uint64PoolSize = 4
)
// Decode a bool.
func (o *Buffer) dec_bool(p *Properties, base structPointer) error {
u, err := p.valDec(o)
if err != nil {
return err
}
if len(o.bools) == 0 {
o.bools = make([]bool, boolPoolSize)
}
o.bools[0] = u != 0
*structPointer_Bool(base, p.field) = &o.bools[0]
o.bools = o.bools[1:]
return nil
}
// Decode an int32.
func (o *Buffer) dec_int32(p *Properties, base structPointer) error {
u, err := p.valDec(o)
if err != nil {
return err
}
word32_Set(structPointer_Word32(base, p.field), o, uint32(u))
return nil
}
// Decode an int64.
func (o *Buffer) dec_int64(p *Properties, base structPointer) error {
u, err := p.valDec(o)
if err != nil {
return err
}
word64_Set(structPointer_Word64(base, p.field), o, u)
return nil
}
// Decode a string.
func (o *Buffer) dec_string(p *Properties, base structPointer) error {
s, err := o.DecodeStringBytes()
if err != nil {
return err
}
sp := new(string)
*sp = s
*structPointer_String(base, p.field) = sp
return nil
}
// Decode a slice of bytes ([]byte).
func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error {
b, err := o.DecodeRawBytes(true)
if err != nil {
return err
}
*structPointer_Bytes(base, p.field) = b
return nil
}
// Decode a slice of bools ([]bool).
func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error {
u, err := p.valDec(o)
if err != nil {
return err
}
v := structPointer_BoolSlice(base, p.field)
*v = append(*v, u != 0)
return nil
}
// Decode a slice of bools ([]bool) in packed format.
func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error {
v := structPointer_BoolSlice(base, p.field)
nn, err := o.DecodeVarint()
if err != nil {
return err
}
nb := int(nn) // number of bytes of encoded bools
y := *v
for i := 0; i < nb; i++ {
u, err := p.valDec(o)
if err != nil {
return err
}
y = append(y, u != 0)
}
*v = y
return nil
}
// Decode a slice of int32s ([]int32).
func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error {
u, err := p.valDec(o)
if err != nil {
return err
}
structPointer_Word32Slice(base, p.field).Append(uint32(u))
return nil
}
// Decode a slice of int32s ([]int32) in packed format.
func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error {
v := structPointer_Word32Slice(base, p.field)
nn, err := o.DecodeVarint()
if err != nil {
return err
}
nb := int(nn) // number of bytes of encoded int32s
fin := o.index + nb
if fin < o.index {
return errOverflow
}
for o.index < fin {
u, err := p.valDec(o)
if err != nil {
return err
}
v.Append(uint32(u))
}
return nil
}
// Decode a slice of int64s ([]int64).
func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error {
u, err := p.valDec(o)
if err != nil {
return err
}
structPointer_Word64Slice(base, p.field).Append(u)
return nil
}
// Decode a slice of int64s ([]int64) in packed format.
func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error {
v := structPointer_Word64Slice(base, p.field)
nn, err := o.DecodeVarint()
if err != nil {
return err
}
nb := int(nn) // number of bytes of encoded int64s
fin := o.index + nb
if fin < o.index {
return errOverflow
}
for o.index < fin {
u, err := p.valDec(o)
if err != nil {
return err
}
v.Append(u)
}
return nil
}
// Decode a slice of strings ([]string).
func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error {
s, err := o.DecodeStringBytes()
if err != nil {
return err
}
v := structPointer_StringSlice(base, p.field)
*v = append(*v, s)
return nil
}
// Decode a slice of slice of bytes ([][]byte).
func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error {
b, err := o.DecodeRawBytes(true)
if err != nil {
return err
}
v := structPointer_BytesSlice(base, p.field)
*v = append(*v, b)
return nil
}
// Decode a group.
func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error {
bas := structPointer_GetStructPointer(base, p.field)
if structPointer_IsNil(bas) {
// allocate new nested message
bas = toStructPointer(reflect.New(p.stype))
structPointer_SetStructPointer(base, p.field, bas)
}
return o.unmarshalType(p.stype, p.sprop, true, bas)
}
// Decode an embedded message.
func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) {
raw, e := o.DecodeRawBytes(false)
if e != nil {
return e
}
bas := structPointer_GetStructPointer(base, p.field)
if structPointer_IsNil(bas) {
// allocate new nested message
bas = toStructPointer(reflect.New(p.stype))
structPointer_SetStructPointer(base, p.field, bas)
}
// If the object can unmarshal itself, let it.
if p.isUnmarshaler {
iv := structPointer_Interface(bas, p.stype)
return iv.(Unmarshaler).Unmarshal(raw)
}
obuf := o.buf
oi := o.index
o.buf = raw
o.index = 0
err = o.unmarshalType(p.stype, p.sprop, false, bas)
o.buf = obuf
o.index = oi
return err
}
// Decode a slice of embedded messages.
func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error {
return o.dec_slice_struct(p, false, base)
}
// Decode a slice of embedded groups.
func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error {
return o.dec_slice_struct(p, true, base)
}
// Decode a slice of structs ([]*struct).
func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error {
v := reflect.New(p.stype)
bas := toStructPointer(v)
structPointer_StructPointerSlice(base, p.field).Append(bas)
if is_group {
err := o.unmarshalType(p.stype, p.sprop, is_group, bas)
return err
}
raw, err := o.DecodeRawBytes(false)
if err != nil {
return err
}
// If the object can unmarshal itself, let it.
if p.isUnmarshaler {
iv := v.Interface()
return iv.(Unmarshaler).Unmarshal(raw)
}
obuf := o.buf
oi := o.index
o.buf = raw
o.index = 0
err = o.unmarshalType(p.stype, p.sprop, is_group, bas)
o.buf = obuf
o.index = oi
return err
}
| 1067282423-goproto000 | proto/decode.go | Go | bsd | 18,475 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
/*
* Types and routines for supporting protocol buffer extensions.
*/
import (
"errors"
"reflect"
"strconv"
"sync"
)
// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
var ErrMissingExtension = errors.New("proto: missing extension")
// ExtensionRange represents a range of message extensions for a protocol buffer.
// Used in code generated by the protocol compiler.
type ExtensionRange struct {
Start, End int32 // both inclusive
}
// extendableProto is an interface implemented by any protocol buffer that may be extended.
type extendableProto interface {
Message
ExtensionRangeArray() []ExtensionRange
ExtensionMap() map[int32]Extension
}
var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem()
// ExtensionDesc represents an extension specification.
// Used in generated code from the protocol compiler.
type ExtensionDesc struct {
ExtendedType Message // nil pointer to the type that is being extended
ExtensionType interface{} // nil pointer to the extension type
Field int32 // field number
Name string // fully-qualified name of extension, for text formatting
Tag string // protobuf tag style
}
func (ed *ExtensionDesc) repeated() bool {
t := reflect.TypeOf(ed.ExtensionType)
return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
}
// Extension represents an extension in a message.
type Extension struct {
// When an extension is stored in a message using SetExtension
// only desc and value are set. When the message is marshaled
// enc will be set to the encoded form of the message.
//
// When a message is unmarshaled and contains extensions, each
// extension will have only enc set. When such an extension is
// accessed using GetExtension (or GetExtensions) desc and value
// will be set.
desc *ExtensionDesc
value interface{}
enc []byte
}
// SetRawExtension is for testing only.
func SetRawExtension(base extendableProto, id int32, b []byte) {
base.ExtensionMap()[id] = Extension{enc: b}
}
// isExtensionField returns true iff the given field number is in an extension range.
func isExtensionField(pb extendableProto, field int32) bool {
for _, er := range pb.ExtensionRangeArray() {
if er.Start <= field && field <= er.End {
return true
}
}
return false
}
// checkExtensionTypes checks that the given extension is valid for pb.
func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
// Check the extended type.
if a, b := reflect.TypeOf(pb), reflect.TypeOf(extension.ExtendedType); a != b {
return errors.New("bad extended type; " + b.String() + " does not extend " + a.String())
}
// Check the range.
if !isExtensionField(pb, extension.Field) {
return errors.New("bad extension number; not in declared ranges")
}
return nil
}
// extPropKey is sufficient to uniquely identify an extension.
type extPropKey struct {
base reflect.Type
field int32
}
var extProp = struct {
sync.RWMutex
m map[extPropKey]*Properties
}{
m: make(map[extPropKey]*Properties),
}
func extensionProperties(ed *ExtensionDesc) *Properties {
key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
extProp.RLock()
if prop, ok := extProp.m[key]; ok {
extProp.RUnlock()
return prop
}
extProp.RUnlock()
extProp.Lock()
defer extProp.Unlock()
// Check again.
if prop, ok := extProp.m[key]; ok {
return prop
}
prop := new(Properties)
prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
extProp.m[key] = prop
return prop
}
// encodeExtensionMap encodes any unmarshaled (unencoded) extensions in m.
func encodeExtensionMap(m map[int32]Extension) error {
for k, e := range m {
if e.value == nil || e.desc == nil {
// Extension is only in its encoded form.
continue
}
// We don't skip extensions that have an encoded form set,
// because the extension value may have been mutated after
// the last time this function was called.
et := reflect.TypeOf(e.desc.ExtensionType)
props := extensionProperties(e.desc)
p := NewBuffer(nil)
// If e.value has type T, the encoder expects a *struct{ X T }.
// Pass a *T with a zero field and hope it all works out.
x := reflect.New(et)
x.Elem().Set(reflect.ValueOf(e.value))
if err := props.enc(p, props, toStructPointer(x)); err != nil {
return err
}
e.enc = p.buf
m[k] = e
}
return nil
}
// HasExtension returns whether the given extension is present in pb.
func HasExtension(pb extendableProto, extension *ExtensionDesc) bool {
// TODO: Check types, field numbers, etc.?
_, ok := pb.ExtensionMap()[extension.Field]
return ok
}
// ClearExtension removes the given extension from pb.
func ClearExtension(pb extendableProto, extension *ExtensionDesc) {
// TODO: Check types, field numbers, etc.?
delete(pb.ExtensionMap(), extension.Field)
}
// GetExtension parses and returns the given extension of pb.
// If the extension is not present it returns ErrMissingExtension.
// If the returned extension is modified, SetExtension must be called
// for the modifications to be reflected in pb.
func GetExtension(pb extendableProto, extension *ExtensionDesc) (interface{}, error) {
if err := checkExtensionTypes(pb, extension); err != nil {
return nil, err
}
e, ok := pb.ExtensionMap()[extension.Field]
if !ok {
return nil, ErrMissingExtension
}
if e.value != nil {
// Already decoded. Check the descriptor, though.
if e.desc != extension {
// This shouldn't happen. If it does, it means that
// GetExtension was called twice with two different
// descriptors with the same field number.
return nil, errors.New("proto: descriptor conflict")
}
return e.value, nil
}
v, err := decodeExtension(e.enc, extension)
if err != nil {
return nil, err
}
// Remember the decoded version and drop the encoded version.
// That way it is safe to mutate what we return.
e.value = v
e.desc = extension
e.enc = nil
return e.value, nil
}
// decodeExtension decodes an extension encoded in b.
func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
o := NewBuffer(b)
t := reflect.TypeOf(extension.ExtensionType)
rep := extension.repeated()
props := extensionProperties(extension)
// t is a pointer to a struct, pointer to basic type or a slice.
// Allocate a "field" to store the pointer/slice itself; the
// pointer/slice will be stored here. We pass
// the address of this field to props.dec.
// This passes a zero field and a *t and lets props.dec
// interpret it as a *struct{ x t }.
value := reflect.New(t).Elem()
for {
// Discard wire type and field number varint. It isn't needed.
if _, err := o.DecodeVarint(); err != nil {
return nil, err
}
if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil {
return nil, err
}
if !rep || o.index >= len(o.buf) {
break
}
}
return value.Interface(), nil
}
// GetExtensions returns a slice of the extensions present in pb that are also listed in es.
// The returned slice has the same length as es; missing extensions will appear as nil elements.
func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
epb, ok := pb.(extendableProto)
if !ok {
err = errors.New("not an extendable proto")
return
}
extensions = make([]interface{}, len(es))
for i, e := range es {
extensions[i], err = GetExtension(epb, e)
if err != nil {
return
}
}
return
}
// SetExtension sets the specified extension of pb to the specified value.
func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{}) error {
if err := checkExtensionTypes(pb, extension); err != nil {
return err
}
typ := reflect.TypeOf(extension.ExtensionType)
if typ != reflect.TypeOf(value) {
return errors.New("bad extension value type")
}
pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value}
return nil
}
// A global registry of extensions.
// The generated code will register the generated descriptors by calling RegisterExtension.
var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
// RegisterExtension is called from the generated code.
func RegisterExtension(desc *ExtensionDesc) {
st := reflect.TypeOf(desc.ExtendedType).Elem()
m := extensionMaps[st]
if m == nil {
m = make(map[int32]*ExtensionDesc)
extensionMaps[st] = m
}
if _, ok := m[desc.Field]; ok {
panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
}
m[desc.Field] = desc
}
// RegisteredExtensions returns a map of the registered extensions of a
// protocol buffer struct, indexed by the extension number.
// The argument pb should be a nil pointer to the struct type.
func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
return extensionMaps[reflect.TypeOf(pb).Elem()]
}
| 1067282423-goproto000 | proto/extensions.go | Go | bsd | 10,595 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
/*
* Routines for encoding data into the wire format for protocol buffers.
*/
import (
"errors"
"reflect"
"sort"
)
// ErrRequiredNotSet is the error returned if Marshal is called with
// a protocol buffer struct whose required fields have not
// all been initialized. It is also the error returned if Unmarshal is
// called with an encoded protocol buffer that does not include all the
// required fields.
type ErrRequiredNotSet struct {
t reflect.Type
}
func (e *ErrRequiredNotSet) Error() string {
return "proto: required fields not set in " + e.t.String()
}
var (
// ErrRepeatedHasNil is the error returned if Marshal is called with
// a struct with a repeated field containing a nil element.
ErrRepeatedHasNil = errors.New("proto: repeated field has nil element")
// ErrNil is the error returned if Marshal is called with nil.
ErrNil = errors.New("proto: Marshal called with nil")
)
// The fundamental encoders that put bytes on the wire.
// Those that take integer types all accept uint64 and are
// therefore of type valueEncoder.
const maxVarintBytes = 10 // maximum length of a varint
// EncodeVarint returns the varint encoding of x.
// This is the format for the
// int32, int64, uint32, uint64, bool, and enum
// protocol buffer types.
// Not used by the package itself, but helpful to clients
// wishing to use the same encoding.
func EncodeVarint(x uint64) []byte {
var buf [maxVarintBytes]byte
var n int
for n = 0; x > 127; n++ {
buf[n] = 0x80 | uint8(x&0x7F)
x >>= 7
}
buf[n] = uint8(x)
n++
return buf[0:n]
}
// EncodeVarint writes a varint-encoded integer to the Buffer.
// This is the format for the
// int32, int64, uint32, uint64, bool, and enum
// protocol buffer types.
func (p *Buffer) EncodeVarint(x uint64) error {
for x >= 1<<7 {
p.buf = append(p.buf, uint8(x&0x7f|0x80))
x >>= 7
}
p.buf = append(p.buf, uint8(x))
return nil
}
// EncodeFixed64 writes a 64-bit integer to the Buffer.
// This is the format for the
// fixed64, sfixed64, and double protocol buffer types.
func (p *Buffer) EncodeFixed64(x uint64) error {
p.buf = append(p.buf,
uint8(x),
uint8(x>>8),
uint8(x>>16),
uint8(x>>24),
uint8(x>>32),
uint8(x>>40),
uint8(x>>48),
uint8(x>>56))
return nil
}
// EncodeFixed32 writes a 32-bit integer to the Buffer.
// This is the format for the
// fixed32, sfixed32, and float protocol buffer types.
func (p *Buffer) EncodeFixed32(x uint64) error {
p.buf = append(p.buf,
uint8(x),
uint8(x>>8),
uint8(x>>16),
uint8(x>>24))
return nil
}
// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
// to the Buffer.
// This is the format used for the sint64 protocol buffer type.
func (p *Buffer) EncodeZigzag64(x uint64) error {
// use signed number to get arithmetic right shift.
return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
// to the Buffer.
// This is the format used for the sint32 protocol buffer type.
func (p *Buffer) EncodeZigzag32(x uint64) error {
// use signed number to get arithmetic right shift.
return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
}
// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
// This is the format used for the bytes protocol buffer
// type and for embedded messages.
func (p *Buffer) EncodeRawBytes(b []byte) error {
p.EncodeVarint(uint64(len(b)))
p.buf = append(p.buf, b...)
return nil
}
// EncodeStringBytes writes an encoded string to the Buffer.
// This is the format used for the proto2 string type.
func (p *Buffer) EncodeStringBytes(s string) error {
p.EncodeVarint(uint64(len(s)))
p.buf = append(p.buf, s...)
return nil
}
// Marshaler is the interface representing objects that can marshal themselves.
type Marshaler interface {
Marshal() ([]byte, error)
}
// Marshal takes the protocol buffer
// and encodes it into the wire format, returning the data.
func Marshal(pb Message) ([]byte, error) {
// Can the object marshal itself?
if m, ok := pb.(Marshaler); ok {
return m.Marshal()
}
p := NewBuffer(nil)
err := p.Marshal(pb)
if err != nil {
return nil, err
}
return p.buf, err
}
// Marshal takes the protocol buffer
// and encodes it into the wire format, writing the result to the
// Buffer.
func (p *Buffer) Marshal(pb Message) error {
// Can the object marshal itself?
if m, ok := pb.(Marshaler); ok {
data, err := m.Marshal()
if err != nil {
return err
}
p.buf = append(p.buf, data...)
return nil
}
t, base, err := getbase(pb)
if structPointer_IsNil(base) {
return ErrNil
}
if err == nil {
err = p.enc_struct(t.Elem(), GetProperties(t.Elem()), base)
}
if collectStats {
stats.Encode++
}
return err
}
// Individual type encoders.
// Encode a bool.
func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
v := *structPointer_Bool(base, p.field)
if v == nil {
return ErrNil
}
x := 0
if *v {
x = 1
}
o.buf = append(o.buf, p.tagcode...)
p.valEnc(o, uint64(x))
return nil
}
// Encode an int32.
func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
v := structPointer_Word32(base, p.field)
if word32_IsNil(v) {
return ErrNil
}
x := word32_Get(v)
o.buf = append(o.buf, p.tagcode...)
p.valEnc(o, uint64(x))
return nil
}
// Encode an int64.
func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
v := structPointer_Word64(base, p.field)
if word64_IsNil(v) {
return ErrNil
}
x := word64_Get(v)
o.buf = append(o.buf, p.tagcode...)
p.valEnc(o, x)
return nil
}
// Encode a string.
func (o *Buffer) enc_string(p *Properties, base structPointer) error {
v := *structPointer_String(base, p.field)
if v == nil {
return ErrNil
}
x := *v
o.buf = append(o.buf, p.tagcode...)
o.EncodeStringBytes(x)
return nil
}
// All protocol buffer fields are nillable, but be careful.
func isNil(v reflect.Value) bool {
switch v.Kind() {
case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
return v.IsNil()
}
return false
}
// Encode a message struct.
func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
structp := structPointer_GetStructPointer(base, p.field)
if structPointer_IsNil(structp) {
return ErrNil
}
// Can the object marshal itself?
if p.isMarshaler {
m := structPointer_Interface(structp, p.stype).(Marshaler)
data, err := m.Marshal()
if err != nil {
return err
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeRawBytes(data)
return nil
}
// need the length before we can write out the message itself,
// so marshal into a separate byte buffer first.
obuf := o.buf
o.buf = o.bufalloc()
err := o.enc_struct(p.stype, p.sprop, structp)
nbuf := o.buf
o.buf = obuf
if err != nil {
o.buffree(nbuf)
return err
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeRawBytes(nbuf)
o.buffree(nbuf)
return nil
}
// Encode a group struct.
func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
b := structPointer_GetStructPointer(base, p.field)
if structPointer_IsNil(b) {
return ErrNil
}
o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
err := o.enc_struct(p.stype, p.sprop, b)
if err != nil {
return err
}
o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
return nil
}
// Encode a slice of bools ([]bool).
func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
s := *structPointer_BoolSlice(base, p.field)
l := len(s)
if l == 0 {
return ErrNil
}
for _, x := range s {
o.buf = append(o.buf, p.tagcode...)
v := uint64(0)
if x {
v = 1
}
p.valEnc(o, v)
}
return nil
}
// Encode a slice of bools ([]bool) in packed format.
func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
s := *structPointer_BoolSlice(base, p.field)
l := len(s)
if l == 0 {
return ErrNil
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
for _, x := range s {
v := uint64(0)
if x {
v = 1
}
p.valEnc(o, v)
}
return nil
}
// Encode a slice of bytes ([]byte).
func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
s := *structPointer_Bytes(base, p.field)
if s == nil {
return ErrNil
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeRawBytes(s)
return nil
}
// Encode a slice of int32s ([]int32).
func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
s := structPointer_Word32Slice(base, p.field)
l := s.Len()
if l == 0 {
return ErrNil
}
for i := 0; i < l; i++ {
o.buf = append(o.buf, p.tagcode...)
x := s.Index(i)
p.valEnc(o, uint64(x))
}
return nil
}
// Encode a slice of int32s ([]int32) in packed format.
func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
s := structPointer_Word32Slice(base, p.field)
l := s.Len()
if l == 0 {
return ErrNil
}
// TODO: Reuse a Buffer.
buf := NewBuffer(nil)
for i := 0; i < l; i++ {
p.valEnc(buf, uint64(s.Index(i)))
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeVarint(uint64(len(buf.buf)))
o.buf = append(o.buf, buf.buf...)
return nil
}
// Encode a slice of int64s ([]int64).
func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
s := structPointer_Word64Slice(base, p.field)
l := s.Len()
if l == 0 {
return ErrNil
}
for i := 0; i < l; i++ {
o.buf = append(o.buf, p.tagcode...)
p.valEnc(o, s.Index(i))
}
return nil
}
// Encode a slice of int64s ([]int64) in packed format.
func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
s := structPointer_Word64Slice(base, p.field)
l := s.Len()
if l == 0 {
return ErrNil
}
// TODO: Reuse a Buffer.
buf := NewBuffer(nil)
for i := 0; i < l; i++ {
p.valEnc(buf, s.Index(i))
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeVarint(uint64(len(buf.buf)))
o.buf = append(o.buf, buf.buf...)
return nil
}
// Encode a slice of slice of bytes ([][]byte).
func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
ss := *structPointer_BytesSlice(base, p.field)
l := len(ss)
if l == 0 {
return ErrNil
}
for i := 0; i < l; i++ {
o.buf = append(o.buf, p.tagcode...)
s := ss[i]
o.EncodeRawBytes(s)
}
return nil
}
// Encode a slice of strings ([]string).
func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
ss := *structPointer_StringSlice(base, p.field)
l := len(ss)
for i := 0; i < l; i++ {
o.buf = append(o.buf, p.tagcode...)
s := ss[i]
o.EncodeStringBytes(s)
}
return nil
}
// Encode a slice of message structs ([]*struct).
func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
s := structPointer_StructPointerSlice(base, p.field)
l := s.Len()
for i := 0; i < l; i++ {
structp := s.Index(i)
if structPointer_IsNil(structp) {
return ErrRepeatedHasNil
}
// Can the object marshal itself?
if p.isMarshaler {
m := structPointer_Interface(structp, p.stype).(Marshaler)
data, err := m.Marshal()
if err != nil {
return err
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeRawBytes(data)
continue
}
obuf := o.buf
o.buf = o.bufalloc()
err := o.enc_struct(p.stype, p.sprop, structp)
nbuf := o.buf
o.buf = obuf
if err != nil {
o.buffree(nbuf)
if err == ErrNil {
return ErrRepeatedHasNil
}
return err
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeRawBytes(nbuf)
o.buffree(nbuf)
}
return nil
}
// Encode a slice of group structs ([]*struct).
func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
s := structPointer_StructPointerSlice(base, p.field)
l := s.Len()
for i := 0; i < l; i++ {
b := s.Index(i)
if structPointer_IsNil(b) {
return ErrRepeatedHasNil
}
o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
err := o.enc_struct(p.stype, p.sprop, b)
if err != nil {
if err == ErrNil {
return ErrRepeatedHasNil
}
return err
}
o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
}
return nil
}
// Encode an extension map.
func (o *Buffer) enc_map(p *Properties, base structPointer) error {
v := *structPointer_ExtMap(base, p.field)
if err := encodeExtensionMap(v); err != nil {
return err
}
// Fast-path for common cases: zero or one extensions.
if len(v) <= 1 {
for _, e := range v {
o.buf = append(o.buf, e.enc...)
}
return nil
}
// Sort keys to provide a deterministic encoding.
keys := make([]int, 0, len(v))
for k := range v {
keys = append(keys, int(k))
}
sort.Ints(keys)
for _, k := range keys {
o.buf = append(o.buf, v[int32(k)].enc...)
}
return nil
}
// Encode a struct.
func (o *Buffer) enc_struct(t reflect.Type, prop *StructProperties, base structPointer) error {
required := prop.reqCount
// Encode fields in tag order so that decoders may use optimizations
// that depend on the ordering.
// http://code.google.com/apis/protocolbuffers/docs/encoding.html#order
for _, i := range prop.order {
p := prop.Prop[i]
if p.enc != nil {
err := p.enc(o, p, base)
if err != nil {
if err != ErrNil {
return err
}
} else if p.Required {
required--
}
}
}
// See if we encoded all required fields.
if required > 0 {
return &ErrRequiredNotSet{t}
}
// Add unrecognized fields at the end.
if prop.unrecField.IsValid() {
v := *structPointer_Bytes(base, prop.unrecField)
if len(v) > 0 {
o.buf = append(o.buf, v...)
}
}
return nil
}
| 1067282423-goproto000 | proto/encode.go | Go | bsd | 15,140 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
// Functions for writing the text protocol buffer format.
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"math"
"os"
"reflect"
"sort"
"strings"
)
var (
newline = []byte("\n")
spaces = []byte(" ")
gtNewline = []byte(">\n")
endBraceNewline = []byte("}\n")
backslashN = []byte{'\\', 'n'}
backslashR = []byte{'\\', 'r'}
backslashT = []byte{'\\', 't'}
backslashDQ = []byte{'\\', '"'}
backslashBS = []byte{'\\', '\\'}
posInf = []byte("inf")
negInf = []byte("-inf")
nan = []byte("nan")
)
type writer interface {
io.Writer
WriteByte(byte) error
}
// textWriter is an io.Writer that tracks its indentation level.
type textWriter struct {
ind int
complete bool // if the current position is a complete line
compact bool // whether to write out as a one-liner
w writer
}
func (w *textWriter) WriteString(s string) (n int, err error) {
if !strings.Contains(s, "\n") {
if !w.compact && w.complete {
w.writeIndent()
}
w.complete = false
return io.WriteString(w.w, s)
}
// WriteString is typically called without newlines, so this
// codepath and its copy are rare. We copy to avoid
// duplicating all of Write's logic here.
return w.Write([]byte(s))
}
func (w *textWriter) Write(p []byte) (n int, err error) {
newlines := bytes.Count(p, newline)
if newlines == 0 {
if !w.compact && w.complete {
w.writeIndent()
}
n, err = w.w.Write(p)
w.complete = false
return n, err
}
frags := bytes.SplitN(p, newline, newlines+1)
if w.compact {
for i, frag := range frags {
if i > 0 {
if err := w.w.WriteByte(' '); err != nil {
return n, err
}
n++
}
nn, err := w.w.Write(frag)
n += nn
if err != nil {
return n, err
}
}
return n, nil
}
for i, frag := range frags {
if w.complete {
w.writeIndent()
}
nn, err := w.w.Write(frag)
n += nn
if err != nil {
return n, err
}
if i+1 < len(frags) {
if err := w.w.WriteByte('\n'); err != nil {
return n, err
}
n++
}
}
w.complete = len(frags[len(frags)-1]) == 0
return n, nil
}
func (w *textWriter) WriteByte(c byte) error {
if w.compact && c == '\n' {
c = ' '
}
if !w.compact && w.complete {
w.writeIndent()
}
err := w.w.WriteByte(c)
w.complete = c == '\n'
return err
}
func (w *textWriter) indent() { w.ind++ }
func (w *textWriter) unindent() {
if w.ind == 0 {
log.Printf("proto: textWriter unindented too far")
return
}
w.ind--
}
func writeName(w *textWriter, props *Properties) error {
if _, err := w.WriteString(props.OrigName); err != nil {
return err
}
if props.Wire != "group" {
return w.WriteByte(':')
}
return nil
}
var (
messageSetType = reflect.TypeOf((*MessageSet)(nil)).Elem()
)
// raw is the interface satisfied by RawMessage.
type raw interface {
Bytes() []byte
}
func writeStruct(w *textWriter, sv reflect.Value) error {
if sv.Type() == messageSetType {
return writeMessageSet(w, sv.Addr().Interface().(*MessageSet))
}
st := sv.Type()
sprops := GetProperties(st)
for i := 0; i < sv.NumField(); i++ {
fv := sv.Field(i)
props := sprops.Prop[i]
name := st.Field(i).Name
if strings.HasPrefix(name, "XXX_") {
// There are two XXX_ fields:
// XXX_unrecognized []byte
// XXX_extensions map[int32]proto.Extension
// The first is handled here;
// the second is handled at the bottom of this function.
if name == "XXX_unrecognized" && !fv.IsNil() {
if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
return err
}
}
continue
}
if fv.Kind() == reflect.Ptr && fv.IsNil() {
// Field not filled in. This could be an optional field or
// a required field that wasn't filled in. Either way, there
// isn't anything we can show for it.
continue
}
if fv.Kind() == reflect.Slice && fv.IsNil() {
// Repeated field that is empty, or a bytes field that is unused.
continue
}
if props.Repeated && fv.Kind() == reflect.Slice {
// Repeated field.
for j := 0; j < fv.Len(); j++ {
if err := writeName(w, props); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte(' '); err != nil {
return err
}
}
if err := writeAny(w, fv.Index(j), props); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
return err
}
}
continue
}
if err := writeName(w, props); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte(' '); err != nil {
return err
}
}
if b, ok := fv.Interface().(raw); ok {
if err := writeRaw(w, b.Bytes()); err != nil {
return err
}
continue
}
// Enums have a String method, so writeAny will work fine.
if err := writeAny(w, fv, props); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
return err
}
}
// Extensions (the XXX_extensions field).
pv := sv.Addr()
if pv.Type().Implements(extendableProtoType) {
if err := writeExtensions(w, pv); err != nil {
return err
}
}
return nil
}
// writeRaw writes an uninterpreted raw message.
func writeRaw(w *textWriter, b []byte) error {
if err := w.WriteByte('<'); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte('\n'); err != nil {
return err
}
}
w.indent()
if err := writeUnknownStruct(w, b); err != nil {
return err
}
w.unindent()
if err := w.WriteByte('>'); err != nil {
return err
}
return nil
}
// writeAny writes an arbitrary field.
func writeAny(w *textWriter, v reflect.Value, props *Properties) error {
v = reflect.Indirect(v)
// Floats have special cases.
if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
x := v.Float()
var b []byte
switch {
case math.IsInf(x, 1):
b = posInf
case math.IsInf(x, -1):
b = negInf
case math.IsNaN(x):
b = nan
}
if b != nil {
_, err := w.Write(b)
return err
}
// Other values are handled below.
}
// We don't attempt to serialise every possible value type; only those
// that can occur in protocol buffers.
switch v.Kind() {
case reflect.Slice:
// Should only be a []byte; repeated fields are handled in writeStruct.
if err := writeString(w, string(v.Interface().([]byte))); err != nil {
return err
}
case reflect.String:
if err := writeString(w, v.String()); err != nil {
return err
}
case reflect.Struct:
// Required/optional group/message.
var bra, ket byte = '<', '>'
if props != nil && props.Wire == "group" {
bra, ket = '{', '}'
}
if err := w.WriteByte(bra); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte('\n'); err != nil {
return err
}
}
w.indent()
if err := writeStruct(w, v); err != nil {
return err
}
w.unindent()
if err := w.WriteByte(ket); err != nil {
return err
}
default:
_, err := fmt.Fprint(w, v.Interface())
return err
}
return nil
}
// equivalent to C's isprint.
func isprint(c byte) bool {
return c >= 0x20 && c < 0x7f
}
// writeString writes a string in the protocol buffer text format.
// It is similar to strconv.Quote except we don't use Go escape sequences,
// we treat the string as a byte sequence, and we use octal escapes.
// These differences are to maintain interoperability with the other
// languages' implementations of the text format.
func writeString(w *textWriter, s string) error {
// use WriteByte here to get any needed indent
if err := w.WriteByte('"'); err != nil {
return err
}
// Loop over the bytes, not the runes.
for i := 0; i < len(s); i++ {
var err error
// Divergence from C++: we don't escape apostrophes.
// There's no need to escape them, and the C++ parser
// copes with a naked apostrophe.
switch c := s[i]; c {
case '\n':
_, err = w.w.Write(backslashN)
case '\r':
_, err = w.w.Write(backslashR)
case '\t':
_, err = w.w.Write(backslashT)
case '"':
_, err = w.w.Write(backslashDQ)
case '\\':
_, err = w.w.Write(backslashBS)
default:
if isprint(c) {
err = w.w.WriteByte(c)
} else {
_, err = fmt.Fprintf(w.w, "\\%03o", c)
}
}
if err != nil {
return err
}
}
return w.WriteByte('"')
}
func writeMessageSet(w *textWriter, ms *MessageSet) error {
for _, item := range ms.Item {
id := *item.TypeId
if msd, ok := messageSetMap[id]; ok {
// Known message set type.
if _, err := fmt.Fprintf(w, "[%s]: <\n", msd.name); err != nil {
return err
}
w.indent()
pb := reflect.New(msd.t.Elem())
if err := Unmarshal(item.Message, pb.Interface().(Message)); err != nil {
if _, err := fmt.Fprintf(w, "/* bad message: %v */\n", err); err != nil {
return err
}
} else {
if err := writeStruct(w, pb.Elem()); err != nil {
return err
}
}
} else {
// Unknown type.
if _, err := fmt.Fprintf(w, "[%d]: <\n", id); err != nil {
return err
}
w.indent()
if err := writeUnknownStruct(w, item.Message); err != nil {
return err
}
}
w.unindent()
if _, err := w.Write(gtNewline); err != nil {
return err
}
}
return nil
}
func writeUnknownStruct(w *textWriter, data []byte) (err error) {
if !w.compact {
if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
return err
}
}
b := NewBuffer(data)
for b.index < len(b.buf) {
x, err := b.DecodeVarint()
if err != nil {
_, err := fmt.Fprintf(w, "/* %v */\n", err)
return err
}
wire, tag := x&7, x>>3
if wire == WireEndGroup {
w.unindent()
if _, err := w.Write(endBraceNewline); err != nil {
return err
}
continue
}
if _, err := fmt.Fprint(w, tag); err != nil {
return err
}
if wire != WireStartGroup {
if err := w.WriteByte(':'); err != nil {
return err
}
}
if !w.compact || wire == WireStartGroup {
if err := w.WriteByte(' '); err != nil {
return err
}
}
switch wire {
case WireBytes:
buf, e := b.DecodeRawBytes(false)
if err == nil {
_, err = fmt.Fprintf(w, "%q", buf)
} else {
_, err = fmt.Fprintf(w, "/* %v */", e)
}
case WireFixed32:
x, err = b.DecodeFixed32()
err = writeUnknownInt(w, x, err)
case WireFixed64:
x, err = b.DecodeFixed64()
err = writeUnknownInt(w, x, err)
case WireStartGroup:
err = w.WriteByte('{')
w.indent()
case WireVarint:
x, err = b.DecodeVarint()
err = writeUnknownInt(w, x, err)
default:
_, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
}
if err != nil {
return err
}
if err = w.WriteByte('\n'); err != nil {
return err
}
}
return nil
}
func writeUnknownInt(w *textWriter, x uint64, err error) error {
if err == nil {
_, err = fmt.Fprint(w, x)
} else {
_, err = fmt.Fprintf(w, "/* %v */", err)
}
return err
}
type int32Slice []int32
func (s int32Slice) Len() int { return len(s) }
func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// writeExtensions writes all the extensions in pv.
// pv is assumed to be a pointer to a protocol message struct that is extendable.
func writeExtensions(w *textWriter, pv reflect.Value) error {
emap := extensionMaps[pv.Type().Elem()]
ep := pv.Interface().(extendableProto)
// Order the extensions by ID.
// This isn't strictly necessary, but it will give us
// canonical output, which will also make testing easier.
m := ep.ExtensionMap()
ids := make([]int32, 0, len(m))
for id := range m {
ids = append(ids, id)
}
sort.Sort(int32Slice(ids))
for _, extNum := range ids {
ext := m[extNum]
var desc *ExtensionDesc
if emap != nil {
desc = emap[extNum]
}
if desc == nil {
// Unknown extension.
if err := writeUnknownStruct(w, ext.enc); err != nil {
return err
}
continue
}
pb, err := GetExtension(ep, desc)
if err != nil {
if _, err := fmt.Fprintln(os.Stderr, "proto: failed getting extension: ", err); err != nil {
return err
}
continue
}
// Repeated extensions will appear as a slice.
if !desc.repeated() {
if err := writeExtension(w, desc.Name, pb); err != nil {
return err
}
} else {
v := reflect.ValueOf(pb)
for i := 0; i < v.Len(); i++ {
if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
return err
}
}
}
}
return nil
}
func writeExtension(w *textWriter, name string, pb interface{}) error {
if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte(' '); err != nil {
return err
}
}
if err := writeAny(w, reflect.ValueOf(pb), nil); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
return err
}
return nil
}
func (w *textWriter) writeIndent() {
if !w.complete {
return
}
remain := w.ind * 2
for remain > 0 {
n := remain
if n > len(spaces) {
n = len(spaces)
}
w.w.Write(spaces[:n])
remain -= n
}
w.complete = false
}
func marshalText(w io.Writer, pb Message, compact bool) error {
val := reflect.ValueOf(pb)
if pb == nil || val.IsNil() {
w.Write([]byte("<nil>"))
return nil
}
var bw *bufio.Writer
ww, ok := w.(writer)
if !ok {
bw = bufio.NewWriter(w)
ww = bw
}
aw := &textWriter{
w: ww,
complete: true,
compact: compact,
}
// Dereference the received pointer so we don't have outer < and >.
v := reflect.Indirect(val)
if err := writeStruct(aw, v); err != nil {
return err
}
if bw != nil {
return bw.Flush()
}
return nil
}
// MarshalText writes a given protocol buffer in text format.
// The only errors returned are from w.
func MarshalText(w io.Writer, pb Message) error { return marshalText(w, pb, false) }
// MarshalTextString is the same as MarshalText, but returns the string directly.
func MarshalTextString(pb Message) string {
var buf bytes.Buffer
marshalText(&buf, pb, false)
return buf.String()
}
// CompactText writes a given protocol buffer in compact text format (one line).
func CompactText(w io.Writer, pb Message) error { return marshalText(w, pb, true) }
// CompactTextString is the same as CompactText, but returns the string directly.
func CompactTextString(pb Message) string {
var buf bytes.Buffer
marshalText(&buf, pb, true)
return buf.String()
}
| 1067282423-goproto000 | proto/text.go | Go | bsd | 15,970 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
/*
* Routines for encoding data into the wire format for protocol buffers.
*/
import (
"fmt"
"os"
"reflect"
"sort"
"strconv"
"strings"
"sync"
)
const debug bool = false
// Constants that identify the encoding of a value on the wire.
const (
WireVarint = 0
WireFixed64 = 1
WireBytes = 2
WireStartGroup = 3
WireEndGroup = 4
WireFixed32 = 5
)
const startSize = 10 // initial slice/string sizes
// Encoders are defined in encoder.go
// An encoder outputs the full representation of a field, including its
// tag and encoder type.
type encoder func(p *Buffer, prop *Properties, base structPointer) error
// A valueEncoder encodes a single integer in a particular encoding.
type valueEncoder func(o *Buffer, x uint64) error
// Decoders are defined in decode.go
// A decoder creates a value from its wire representation.
// Unrecognized subelements are saved in unrec.
type decoder func(p *Buffer, prop *Properties, base structPointer) error
// A valueDecoder decodes a single integer in a particular encoding.
type valueDecoder func(o *Buffer) (x uint64, err error)
// tagMap is an optimization over map[int]int for typical protocol buffer
// use-cases. Encoded protocol buffers are often in tag order with small tag
// numbers.
type tagMap struct {
fastTags []int
slowTags map[int]int
}
// tagMapFastLimit is the upper bound on the tag number that will be stored in
// the tagMap slice rather than its map.
const tagMapFastLimit = 1024
func (p *tagMap) get(t int) (int, bool) {
if t > 0 && t < tagMapFastLimit {
if t >= len(p.fastTags) {
return 0, false
}
fi := p.fastTags[t]
return fi, fi >= 0
}
fi, ok := p.slowTags[t]
return fi, ok
}
func (p *tagMap) put(t int, fi int) {
if t > 0 && t < tagMapFastLimit {
for len(p.fastTags) < t+1 {
p.fastTags = append(p.fastTags, -1)
}
p.fastTags[t] = fi
return
}
if p.slowTags == nil {
p.slowTags = make(map[int]int)
}
p.slowTags[t] = fi
}
// StructProperties represents properties for all the fields of a struct.
// decoderTags and decoderOrigNames should only be used by the decoder.
type StructProperties struct {
Prop []*Properties // properties for each field
reqCount int // required count
decoderTags tagMap // map from proto tag to struct field number
decoderOrigNames map[string]int // map from original name to struct field number
order []int // list of struct field numbers in tag order
unrecField field // field id of the XXX_unrecognized []byte field
extendable bool // is this an extendable proto
}
// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
// See encoder.go, (*Buffer).enc_struct.
func (sp *StructProperties) Len() int { return len(sp.order) }
func (sp *StructProperties) Less(i, j int) bool {
return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
}
func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
// Properties represents the protocol-specific behavior of a single struct field.
type Properties struct {
Name string // name of the field, for error messages
OrigName string // original name before protocol compiler (always set)
Wire string
WireType int
Tag int
Required bool
Optional bool
Repeated bool
Packed bool // relevant for repeated primitives only
Enum string // set for enum types only
Default string // default value
def_uint64 uint64
enc encoder
valEnc valueEncoder // set for bool and numeric types only
field field
tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType)
tagbuf [8]byte
stype reflect.Type // set for struct types only
sprop *StructProperties // set for struct types only
isMarshaler bool
isUnmarshaler bool
dec decoder
valDec valueDecoder // set for bool and numeric types only
// If this is a packable field, this will be the decoder for the packed version of the field.
packedDec decoder
}
// String formats the properties in the protobuf struct field tag style.
func (p *Properties) String() string {
s := p.Wire
s = ","
s += strconv.Itoa(p.Tag)
if p.Required {
s += ",req"
}
if p.Optional {
s += ",opt"
}
if p.Repeated {
s += ",rep"
}
if p.Packed {
s += ",packed"
}
if p.OrigName != p.Name {
s += ",name=" + p.OrigName
}
if len(p.Enum) > 0 {
s += ",enum=" + p.Enum
}
if len(p.Default) > 0 {
s += ",def=" + p.Default
}
return s
}
// Parse populates p by parsing a string in the protobuf struct field tag style.
func (p *Properties) Parse(s string) {
// "bytes,49,opt,name=foo,def=hello!"
fields := strings.Split(s, ",") // breaks def=, but handled below.
if len(fields) < 2 {
fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
return
}
p.Wire = fields[0]
switch p.Wire {
case "varint":
p.WireType = WireVarint
p.valEnc = (*Buffer).EncodeVarint
p.valDec = (*Buffer).DecodeVarint
case "fixed32":
p.WireType = WireFixed32
p.valEnc = (*Buffer).EncodeFixed32
p.valDec = (*Buffer).DecodeFixed32
case "fixed64":
p.WireType = WireFixed64
p.valEnc = (*Buffer).EncodeFixed64
p.valDec = (*Buffer).DecodeFixed64
case "zigzag32":
p.WireType = WireVarint
p.valEnc = (*Buffer).EncodeZigzag32
p.valDec = (*Buffer).DecodeZigzag32
case "zigzag64":
p.WireType = WireVarint
p.valEnc = (*Buffer).EncodeZigzag64
p.valDec = (*Buffer).DecodeZigzag64
case "bytes", "group":
p.WireType = WireBytes
// no numeric converter for non-numeric types
default:
fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
return
}
var err error
p.Tag, err = strconv.Atoi(fields[1])
if err != nil {
return
}
for i := 2; i < len(fields); i++ {
f := fields[i]
switch {
case f == "req":
p.Required = true
case f == "opt":
p.Optional = true
case f == "rep":
p.Repeated = true
case f == "packed":
p.Packed = true
case strings.HasPrefix(f, "name="):
p.OrigName = f[5:]
case strings.HasPrefix(f, "enum="):
p.Enum = f[5:]
case strings.HasPrefix(f, "def="):
p.Default = f[4:] // rest of string
if i+1 < len(fields) {
// Commas aren't escaped, and def is always last.
p.Default += "," + strings.Join(fields[i+1:], ",")
break
}
}
}
}
func logNoSliceEnc(t1, t2 reflect.Type) {
fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2)
}
var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
// Initialize the fields for encoding and decoding.
func (p *Properties) setEncAndDec(typ reflect.Type, lockGetProp bool) {
p.enc = nil
p.dec = nil
switch t1 := typ; t1.Kind() {
default:
fmt.Fprintf(os.Stderr, "proto: no coders for %T\n", t1)
case reflect.Ptr:
switch t2 := t1.Elem(); t2.Kind() {
default:
fmt.Fprintf(os.Stderr, "proto: no encoder function for %T -> %T\n", t1, t2)
break
case reflect.Bool:
p.enc = (*Buffer).enc_bool
p.dec = (*Buffer).dec_bool
case reflect.Int32, reflect.Uint32:
p.enc = (*Buffer).enc_int32
p.dec = (*Buffer).dec_int32
case reflect.Int64, reflect.Uint64:
p.enc = (*Buffer).enc_int64
p.dec = (*Buffer).dec_int64
case reflect.Float32:
p.enc = (*Buffer).enc_int32 // can just treat them as bits
p.dec = (*Buffer).dec_int32
case reflect.Float64:
p.enc = (*Buffer).enc_int64 // can just treat them as bits
p.dec = (*Buffer).dec_int64
case reflect.String:
p.enc = (*Buffer).enc_string
p.dec = (*Buffer).dec_string
case reflect.Struct:
p.stype = t1.Elem()
p.isMarshaler = isMarshaler(t1)
p.isUnmarshaler = isUnmarshaler(t1)
if p.Wire == "bytes" {
p.enc = (*Buffer).enc_struct_message
p.dec = (*Buffer).dec_struct_message
} else {
p.enc = (*Buffer).enc_struct_group
p.dec = (*Buffer).dec_struct_group
}
}
case reflect.Slice:
switch t2 := t1.Elem(); t2.Kind() {
default:
logNoSliceEnc(t1, t2)
break
case reflect.Bool:
if p.Packed {
p.enc = (*Buffer).enc_slice_packed_bool
} else {
p.enc = (*Buffer).enc_slice_bool
}
p.dec = (*Buffer).dec_slice_bool
p.packedDec = (*Buffer).dec_slice_packed_bool
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
switch t2.Bits() {
case 32:
if p.Packed {
p.enc = (*Buffer).enc_slice_packed_int32
} else {
p.enc = (*Buffer).enc_slice_int32
}
p.dec = (*Buffer).dec_slice_int32
p.packedDec = (*Buffer).dec_slice_packed_int32
case 64:
if p.Packed {
p.enc = (*Buffer).enc_slice_packed_int64
} else {
p.enc = (*Buffer).enc_slice_int64
}
p.dec = (*Buffer).dec_slice_int64
p.packedDec = (*Buffer).dec_slice_packed_int64
case 8:
if t2.Kind() == reflect.Uint8 {
p.enc = (*Buffer).enc_slice_byte
p.dec = (*Buffer).dec_slice_byte
}
default:
logNoSliceEnc(t1, t2)
break
}
case reflect.Float32, reflect.Float64:
switch t2.Bits() {
case 32:
// can just treat them as bits
if p.Packed {
p.enc = (*Buffer).enc_slice_packed_int32
} else {
p.enc = (*Buffer).enc_slice_int32
}
p.dec = (*Buffer).dec_slice_int32
p.packedDec = (*Buffer).dec_slice_packed_int32
case 64:
// can just treat them as bits
if p.Packed {
p.enc = (*Buffer).enc_slice_packed_int64
} else {
p.enc = (*Buffer).enc_slice_int64
}
p.dec = (*Buffer).dec_slice_int64
p.packedDec = (*Buffer).dec_slice_packed_int64
default:
logNoSliceEnc(t1, t2)
break
}
case reflect.String:
p.enc = (*Buffer).enc_slice_string
p.dec = (*Buffer).dec_slice_string
case reflect.Ptr:
switch t3 := t2.Elem(); t3.Kind() {
default:
fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3)
break
case reflect.Struct:
p.stype = t2.Elem()
p.isMarshaler = isMarshaler(t2)
p.isUnmarshaler = isUnmarshaler(t2)
p.enc = (*Buffer).enc_slice_struct_group
p.dec = (*Buffer).dec_slice_struct_group
if p.Wire == "bytes" {
p.enc = (*Buffer).enc_slice_struct_message
p.dec = (*Buffer).dec_slice_struct_message
}
}
case reflect.Slice:
switch t2.Elem().Kind() {
default:
fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem())
break
case reflect.Uint8:
p.enc = (*Buffer).enc_slice_slice_byte
p.dec = (*Buffer).dec_slice_slice_byte
}
}
}
// precalculate tag code
wire := p.WireType
if p.Packed {
wire = WireBytes
}
x := uint32(p.Tag)<<3 | uint32(wire)
i := 0
for i = 0; x > 127; i++ {
p.tagbuf[i] = 0x80 | uint8(x&0x7F)
x >>= 7
}
p.tagbuf[i] = uint8(x)
p.tagcode = p.tagbuf[0 : i+1]
if p.stype != nil {
if lockGetProp {
p.sprop = GetProperties(p.stype)
} else {
p.sprop = getPropertiesLocked(p.stype)
}
}
}
var (
marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
)
// isMarshaler reports whether type t implements Marshaler.
func isMarshaler(t reflect.Type) bool {
// We're checking for (likely) pointer-receiver methods
// so if t is not a pointer, something is very wrong.
// The calls above only invoke isMarshaler on pointer types.
if t.Kind() != reflect.Ptr {
panic("proto: misuse of isMarshaler")
}
return t.Implements(marshalerType)
}
// isUnmarshaler reports whether type t implements Unmarshaler.
func isUnmarshaler(t reflect.Type) bool {
// We're checking for (likely) pointer-receiver methods
// so if t is not a pointer, something is very wrong.
// The calls above only invoke isUnmarshaler on pointer types.
if t.Kind() != reflect.Ptr {
panic("proto: misuse of isUnmarshaler")
}
return t.Implements(unmarshalerType)
}
// Init populates the properties from a protocol buffer struct tag.
func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
p.init(typ, name, tag, f, true)
}
func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
// "bytes,49,opt,def=hello!"
p.Name = name
p.OrigName = name
if f != nil {
p.field = toField(f)
}
if tag == "" {
return
}
p.Parse(tag)
p.setEncAndDec(typ, lockGetProp)
}
var (
mutex sync.Mutex
propertiesMap = make(map[reflect.Type]*StructProperties)
)
// GetProperties returns the list of properties for the type represented by t.
func GetProperties(t reflect.Type) *StructProperties {
mutex.Lock()
sprop := getPropertiesLocked(t)
mutex.Unlock()
return sprop
}
// getPropertiesLocked requires that mutex is held.
func getPropertiesLocked(t reflect.Type) *StructProperties {
if prop, ok := propertiesMap[t]; ok {
if collectStats {
stats.Chit++
}
return prop
}
if collectStats {
stats.Cmiss++
}
prop := new(StructProperties)
// in case of recursive protos, fill this in now.
propertiesMap[t] = prop
// build properties
prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType)
prop.unrecField = invalidField
prop.Prop = make([]*Properties, t.NumField())
prop.order = make([]int, t.NumField())
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
p := new(Properties)
name := f.Name
p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
if f.Name == "XXX_extensions" { // special case
p.enc = (*Buffer).enc_map
p.dec = nil // not needed
}
if f.Name == "XXX_unrecognized" { // special case
prop.unrecField = toField(&f)
}
prop.Prop[i] = p
prop.order[i] = i
if debug {
print(i, " ", f.Name, " ", t.String(), " ")
if p.Tag > 0 {
print(p.String())
}
print("\n")
}
if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") {
fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]")
}
}
// Re-order prop.order.
sort.Sort(prop)
// build required counts
// build tags
reqCount := 0
prop.decoderOrigNames = make(map[string]int)
for i, p := range prop.Prop {
if strings.HasPrefix(p.Name, "XXX_") {
// Internal fields should not appear in tags/origNames maps.
// They are handled specially when encoding and decoding.
continue
}
if p.Required {
reqCount++
}
prop.decoderTags.put(p.Tag, i)
prop.decoderOrigNames[p.OrigName] = i
}
prop.reqCount = reqCount
return prop
}
// Return the Properties object for the x[0]'th field of the structure.
func propByIndex(t reflect.Type, x []int) *Properties {
if len(x) != 1 {
fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t)
return nil
}
prop := GetProperties(t)
return prop.Prop[x[0]]
}
// Get the address and type of a pointer to a struct from an interface.
func getbase(pb Message) (t reflect.Type, b structPointer, err error) {
if pb == nil {
err = ErrNil
return
}
// get the reflect type of the pointer to the struct.
t = reflect.TypeOf(pb)
// get the address of the struct.
value := reflect.ValueOf(pb)
b = toStructPointer(value)
return
}
// A global registry of enum types.
// The generated code will register the generated maps by calling RegisterEnum.
var enumValueMaps = make(map[string]map[string]int32)
// RegisterEnum is called from the generated code to install the enum descriptor
// maps into the global table to aid parsing text format protocol buffers.
func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
if _, ok := enumValueMaps[typeName]; ok {
panic("proto: duplicate enum registered: " + typeName)
}
enumValueMaps[typeName] = valueMap
}
| 1067282423-goproto000 | proto/properties.go | Go | bsd | 17,388 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
Package proto converts data structures to and from the wire format of
protocol buffers. It works in concert with the Go source code generated
for .proto files by the protocol compiler.
A summary of the properties of the protocol buffer interface
for a protocol buffer variable v:
- Names are turned from camel_case to CamelCase for export.
- There are no methods on v to set fields; just treat
them as structure fields.
- There are getters that return a field's value if set,
and return the field's default value if unset.
The getters work even if the receiver is a nil message.
- The zero value for a struct is its correct initialization state.
All desired fields must be set before marshaling.
- A Reset() method will restore a protobuf struct to its zero state.
- Non-repeated fields are pointers to the values; nil means unset.
That is, optional or required field int32 f becomes F *int32.
- Repeated fields are slices.
- Helper functions are available to aid the setting of fields.
Helpers for getting values are superseded by the
GetFoo methods and their use is deprecated.
msg.Foo = proto.String("hello") // set field
- Constants are defined to hold the default values of all fields that
have them. They have the form Default_StructName_FieldName.
Because the getter methods handle defaulted values,
direct use of these constants should be rare.
- Enums are given type names and maps from names to values.
Enum values are prefixed with the enum's type name. Enum types have
a String method, and a Enum method to assist in message construction.
- Nested groups and enums have type names prefixed with the name of
the surrounding message type.
- Extensions are given descriptor names that start with E_,
followed by an underscore-delimited list of the nested messages
that contain it (if any) followed by the CamelCased name of the
extension field itself. HasExtension, ClearExtension, GetExtension
and SetExtension are functions for manipulating extensions.
- Marshal and Unmarshal are functions to encode and decode the wire format.
The simplest way to describe this is to see an example.
Given file test.proto, containing
package example;
enum FOO { X = 17; };
message Test {
required string label = 1;
optional int32 type = 2 [default=77];
repeated int64 reps = 3;
optional group OptionalGroup = 4 {
required string RequiredField = 5;
}
}
The resulting file, test.pb.go, is:
package example
import "code.google.com/p/goprotobuf/proto"
type FOO int32
const (
FOO_X FOO = 17
)
var FOO_name = map[int32]string{
17: "X",
}
var FOO_value = map[string]int32{
"X": 17,
}
func (x FOO) Enum() *FOO {
p := new(FOO)
*p = x
return p
}
func (x FOO) String() string {
return proto.EnumName(FOO_name, int32(x))
}
type Test struct {
Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (this *Test) Reset() { *this = Test{} }
func (this *Test) String() string { return proto.CompactTextString(this) }
const Default_Test_Type int32 = 77
func (this *Test) GetLabel() string {
if this != nil && this.Label != nil {
return *this.Label
}
return ""
}
func (this *Test) GetType() int32 {
if this != nil && this.Type != nil {
return *this.Type
}
return Default_Test_Type
}
func (this *Test) GetOptionalgroup() *Test_OptionalGroup {
if this != nil {
return this.Optionalgroup
}
return nil
}
type Test_OptionalGroup struct {
RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (this *Test_OptionalGroup) Reset() { *this = Test_OptionalGroup{} }
func (this *Test_OptionalGroup) String() string { return proto.CompactTextString(this) }
func (this *Test_OptionalGroup) GetRequiredField() string {
if this != nil && this.RequiredField != nil {
return *this.RequiredField
}
return ""
}
func init() {
proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
}
To create and play with a Test object:
package main
import (
"log"
"code.google.com/p/goprotobuf/proto"
"./example.pb"
)
func main() {
test := &example.Test{
Label: proto.String("hello"),
Type: proto.Int32(17),
Optionalgroup: &example.Test_OptionalGroup{
RequiredField: proto.String("good bye"),
},
}
data, err := proto.Marshal(test)
if err != nil {
log.Fatal("marshaling error: ", err)
}
newTest := new(example.Test)
err = proto.Unmarshal(data, newTest)
if err != nil {
log.Fatal("unmarshaling error: ", err)
}
// Now test and newTest contain the same data.
if test.GetLabel() != newTest.GetLabel() {
log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
}
// etc.
}
*/
package proto
import (
"encoding/json"
"fmt"
"log"
"reflect"
"strconv"
"sync"
)
// Message is implemented by generated protocol buffer messages.
type Message interface {
Reset()
String() string
ProtoMessage()
}
// Stats records allocation details about the protocol buffer encoders
// and decoders. Useful for tuning the library itself.
type Stats struct {
Emalloc uint64 // mallocs in encode
Dmalloc uint64 // mallocs in decode
Encode uint64 // number of encodes
Decode uint64 // number of decodes
Chit uint64 // number of cache hits
Cmiss uint64 // number of cache misses
}
// Set to true to enable stats collection.
const collectStats = false
var stats Stats
// GetStats returns a copy of the global Stats structure.
func GetStats() Stats { return stats }
// A Buffer is a buffer manager for marshaling and unmarshaling
// protocol buffers. It may be reused between invocations to
// reduce memory usage. It is not necessary to use a Buffer;
// the global functions Marshal and Unmarshal create a
// temporary Buffer and are fine for most applications.
type Buffer struct {
buf []byte // encode/decode byte stream
index int // write point
freelist [10][]byte // list of available buffers
nfreelist int // number of free buffers
// pools of basic types to amortize allocation.
bools []bool
uint32s []uint32
uint64s []uint64
// extra pools, only used with pointer_reflect.go
int32s []int32
int64s []int64
float32s []float32
float64s []float64
}
// NewBuffer allocates a new Buffer and initializes its internal data to
// the contents of the argument slice.
func NewBuffer(e []byte) *Buffer {
p := new(Buffer)
if e == nil {
e = p.bufalloc()
}
p.buf = e
p.index = 0
return p
}
// Reset resets the Buffer, ready for marshaling a new protocol buffer.
func (p *Buffer) Reset() {
if p.buf == nil {
p.buf = p.bufalloc()
}
p.buf = p.buf[0:0] // for reading/writing
p.index = 0 // for reading
}
// SetBuf replaces the internal buffer with the slice,
// ready for unmarshaling the contents of the slice.
func (p *Buffer) SetBuf(s []byte) {
p.buf = s
p.index = 0
}
// Bytes returns the contents of the Buffer.
func (p *Buffer) Bytes() []byte { return p.buf }
// Allocate a buffer for the Buffer.
func (p *Buffer) bufalloc() []byte {
if p.nfreelist > 0 {
// reuse an old one
p.nfreelist--
s := p.freelist[p.nfreelist]
return s[0:0]
}
// make a new one
s := make([]byte, 0, 16)
return s
}
// Free (and remember in freelist) a byte buffer for the Buffer.
func (p *Buffer) buffree(s []byte) {
if p.nfreelist < len(p.freelist) {
// Take next slot.
p.freelist[p.nfreelist] = s
p.nfreelist++
return
}
// Find the smallest.
besti := -1
bestl := len(s)
for i, b := range p.freelist {
if len(b) < bestl {
besti = i
bestl = len(b)
}
}
// Overwrite the smallest.
if besti >= 0 {
p.freelist[besti] = s
}
}
/*
* Helper routines for simplifying the creation of optional fields of basic type.
*/
// Bool is a helper routine that allocates a new bool value
// to store v and returns a pointer to it.
func Bool(v bool) *bool {
p := new(bool)
*p = v
return p
}
// Int32 is a helper routine that allocates a new int32 value
// to store v and returns a pointer to it.
func Int32(v int32) *int32 {
p := new(int32)
*p = v
return p
}
// Int is a helper routine that allocates a new int32 value
// to store v and returns a pointer to it, but unlike Int32
// its argument value is an int.
func Int(v int) *int32 {
p := new(int32)
*p = int32(v)
return p
}
// Int64 is a helper routine that allocates a new int64 value
// to store v and returns a pointer to it.
func Int64(v int64) *int64 {
p := new(int64)
*p = v
return p
}
// Float32 is a helper routine that allocates a new float32 value
// to store v and returns a pointer to it.
func Float32(v float32) *float32 {
p := new(float32)
*p = v
return p
}
// Float64 is a helper routine that allocates a new float64 value
// to store v and returns a pointer to it.
func Float64(v float64) *float64 {
p := new(float64)
*p = v
return p
}
// Uint32 is a helper routine that allocates a new uint32 value
// to store v and returns a pointer to it.
func Uint32(v uint32) *uint32 {
p := new(uint32)
*p = v
return p
}
// Uint64 is a helper routine that allocates a new uint64 value
// to store v and returns a pointer to it.
func Uint64(v uint64) *uint64 {
p := new(uint64)
*p = v
return p
}
// String is a helper routine that allocates a new string value
// to store v and returns a pointer to it.
func String(v string) *string {
p := new(string)
*p = v
return p
}
// EnumName is a helper function to simplify printing protocol buffer enums
// by name. Given an enum map and a value, it returns a useful string.
func EnumName(m map[int32]string, v int32) string {
s, ok := m[v]
if ok {
return s
}
return strconv.Itoa(int(v))
}
// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
// from their JSON-encoded representation. Given a map from the enum's symbolic
// names to its int values, and a byte buffer containing the JSON-encoded
// value, it returns an int32 that can be cast to the enum type by the caller.
//
// The function can deal with older JSON representations, which represented
// enums directly by their int32 values, or with newer representations, which
// use the symbolic name as a string.
func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
if data[0] == '"' {
// New style: enums are strings.
var repr string
if err := json.Unmarshal(data, &repr); err != nil {
return -1, err
}
val, ok := m[repr]
if !ok {
return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
}
return val, nil
}
// Old style: enums are ints.
var val int32
if err := json.Unmarshal(data, &val); err != nil {
return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
}
return val, nil
}
// DebugPrint dumps the encoded data in b in a debugging format with a header
// including the string s. Used in testing but made available for general debugging.
func (o *Buffer) DebugPrint(s string, b []byte) {
var u uint64
obuf := o.buf
index := o.index
o.buf = b
o.index = 0
depth := 0
fmt.Printf("\n--- %s ---\n", s)
out:
for {
for i := 0; i < depth; i++ {
fmt.Print(" ")
}
index := o.index
if index == len(o.buf) {
break
}
op, err := o.DecodeVarint()
if err != nil {
fmt.Printf("%3d: fetching op err %v\n", index, err)
break out
}
tag := op >> 3
wire := op & 7
switch wire {
default:
fmt.Printf("%3d: t=%3d unknown wire=%d\n",
index, tag, wire)
break out
case WireBytes:
var r []byte
r, err = o.DecodeRawBytes(false)
if err != nil {
break out
}
fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
if len(r) <= 6 {
for i := 0; i < len(r); i++ {
fmt.Printf(" %.2x", r[i])
}
} else {
for i := 0; i < 3; i++ {
fmt.Printf(" %.2x", r[i])
}
fmt.Printf(" ..")
for i := len(r) - 3; i < len(r); i++ {
fmt.Printf(" %.2x", r[i])
}
}
fmt.Printf("\n")
case WireFixed32:
u, err = o.DecodeFixed32()
if err != nil {
fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
break out
}
fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
case WireFixed64:
u, err = o.DecodeFixed64()
if err != nil {
fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
break out
}
fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
break
case WireVarint:
u, err = o.DecodeVarint()
if err != nil {
fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
break out
}
fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
case WireStartGroup:
if err != nil {
fmt.Printf("%3d: t=%3d start err %v\n", index, tag, err)
break out
}
fmt.Printf("%3d: t=%3d start\n", index, tag)
depth++
case WireEndGroup:
depth--
if err != nil {
fmt.Printf("%3d: t=%3d end err %v\n", index, tag, err)
break out
}
fmt.Printf("%3d: t=%3d end\n", index, tag)
}
}
if depth != 0 {
fmt.Printf("%3d: start-end not balanced %d\n", o.index, depth)
}
fmt.Printf("\n")
o.buf = obuf
o.index = index
}
// SetDefaults sets unset protocol buffer fields to their default values.
// It only modifies fields that are both unset and have defined defaults.
// It recursively sets default values in any non-nil sub-messages.
func SetDefaults(pb Message) {
setDefaults(reflect.ValueOf(pb), true, false)
}
// v is a pointer to a struct.
func setDefaults(v reflect.Value, recur, zeros bool) {
v = v.Elem()
defaultMu.RLock()
dm, ok := defaults[v.Type()]
defaultMu.RUnlock()
if !ok {
dm = buildDefaultMessage(v.Type())
defaultMu.Lock()
defaults[v.Type()] = dm
defaultMu.Unlock()
}
for _, sf := range dm.scalars {
f := v.Field(sf.index)
if !f.IsNil() {
// field already set
continue
}
dv := sf.value
if dv == nil && !zeros {
// no explicit default, and don't want to set zeros
continue
}
fptr := f.Addr().Interface() // **T
// TODO: Consider batching the allocations we do here.
switch sf.kind {
case reflect.Bool:
b := new(bool)
if dv != nil {
*b = dv.(bool)
}
*(fptr.(**bool)) = b
case reflect.Float32:
f := new(float32)
if dv != nil {
*f = dv.(float32)
}
*(fptr.(**float32)) = f
case reflect.Float64:
f := new(float64)
if dv != nil {
*f = dv.(float64)
}
*(fptr.(**float64)) = f
case reflect.Int32:
// might be an enum
if ft := f.Type(); ft != int32PtrType {
// enum
f.Set(reflect.New(ft.Elem()))
if dv != nil {
f.Elem().SetInt(int64(dv.(int32)))
}
} else {
// int32 field
i := new(int32)
if dv != nil {
*i = dv.(int32)
}
*(fptr.(**int32)) = i
}
case reflect.Int64:
i := new(int64)
if dv != nil {
*i = dv.(int64)
}
*(fptr.(**int64)) = i
case reflect.String:
s := new(string)
if dv != nil {
*s = dv.(string)
}
*(fptr.(**string)) = s
case reflect.Uint8:
// exceptional case: []byte
var b []byte
if dv != nil {
db := dv.([]byte)
b = make([]byte, len(db))
copy(b, db)
} else {
b = []byte{}
}
*(fptr.(*[]byte)) = b
case reflect.Uint32:
u := new(uint32)
if dv != nil {
*u = dv.(uint32)
}
*(fptr.(**uint32)) = u
case reflect.Uint64:
u := new(uint64)
if dv != nil {
*u = dv.(uint64)
}
*(fptr.(**uint64)) = u
default:
log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
}
}
for _, ni := range dm.nested {
f := v.Field(ni)
if f.IsNil() {
continue
}
// f is *T or []*T
if f.Kind() == reflect.Ptr {
setDefaults(f, recur, zeros)
} else {
for i := 0; i < f.Len(); i++ {
e := f.Index(i)
if e.IsNil() {
continue
}
setDefaults(e, recur, zeros)
}
}
}
}
var (
// defaults maps a protocol buffer struct type to a slice of the fields,
// with its scalar fields set to their proto-declared non-zero default values.
defaultMu sync.RWMutex
defaults = make(map[reflect.Type]defaultMessage)
int32PtrType = reflect.TypeOf((*int32)(nil))
)
// defaultMessage represents information about the default values of a message.
type defaultMessage struct {
scalars []scalarField
nested []int // struct field index of nested messages
}
type scalarField struct {
index int // struct field index
kind reflect.Kind // element type (the T in *T or []T)
value interface{} // the proto-declared default value, or nil
}
func ptrToStruct(t reflect.Type) bool {
return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
}
// t is a struct type.
func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
sprop := GetProperties(t)
for _, prop := range sprop.Prop {
fi, ok := sprop.decoderTags.get(prop.Tag)
if !ok {
// XXX_unrecognized
continue
}
ft := t.Field(fi).Type
// nested messages
if ptrToStruct(ft) || (ft.Kind() == reflect.Slice && ptrToStruct(ft.Elem())) {
dm.nested = append(dm.nested, fi)
continue
}
sf := scalarField{
index: fi,
kind: ft.Elem().Kind(),
}
// scalar fields without defaults
if prop.Default == "" {
dm.scalars = append(dm.scalars, sf)
continue
}
// a scalar field: either *T or []byte
switch ft.Elem().Kind() {
case reflect.Bool:
x, err := strconv.ParseBool(prop.Default)
if err != nil {
log.Printf("proto: bad default bool %q: %v", prop.Default, err)
continue
}
sf.value = x
case reflect.Float32:
x, err := strconv.ParseFloat(prop.Default, 32)
if err != nil {
log.Printf("proto: bad default float32 %q: %v", prop.Default, err)
continue
}
sf.value = float32(x)
case reflect.Float64:
x, err := strconv.ParseFloat(prop.Default, 64)
if err != nil {
log.Printf("proto: bad default float64 %q: %v", prop.Default, err)
continue
}
sf.value = x
case reflect.Int32:
x, err := strconv.ParseInt(prop.Default, 10, 32)
if err != nil {
log.Printf("proto: bad default int32 %q: %v", prop.Default, err)
continue
}
sf.value = int32(x)
case reflect.Int64:
x, err := strconv.ParseInt(prop.Default, 10, 64)
if err != nil {
log.Printf("proto: bad default int64 %q: %v", prop.Default, err)
continue
}
sf.value = x
case reflect.String:
sf.value = prop.Default
case reflect.Uint8:
// []byte (not *uint8)
sf.value = []byte(prop.Default)
case reflect.Uint32:
x, err := strconv.ParseUint(prop.Default, 10, 32)
if err != nil {
log.Printf("proto: bad default uint32 %q: %v", prop.Default, err)
continue
}
sf.value = uint32(x)
case reflect.Uint64:
x, err := strconv.ParseUint(prop.Default, 10, 64)
if err != nil {
log.Printf("proto: bad default uint64 %q: %v", prop.Default, err)
continue
}
sf.value = x
default:
log.Printf("proto: unhandled def kind %v", ft.Elem().Kind())
continue
}
dm.scalars = append(dm.scalars, sf)
}
return dm
}
| 1067282423-goproto000 | proto/lib.go | Go | bsd | 21,132 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2012 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// +build appengine
// This file contains an implementation of proto field accesses using package reflect.
// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
// be used on App Engine.
package proto
import (
"math"
"reflect"
)
// A structPointer is a pointer to a struct.
type structPointer struct {
v reflect.Value
}
// toStructPointer returns a structPointer equivalent to the given reflect value.
// The reflect value must itself be a pointer to a struct.
func toStructPointer(v reflect.Value) structPointer {
return structPointer{v}
}
// IsNil reports whether p is nil.
func structPointer_IsNil(p structPointer) bool {
return p.v.IsNil()
}
// Interface returns the struct pointer as an interface value.
func structPointer_Interface(p structPointer, _ reflect.Type) interface{} {
return p.v.Interface()
}
// A field identifies a field in a struct, accessible from a structPointer.
// In this implementation, a field is identified by the sequence of field indices
// passed to reflect's FieldByIndex.
type field []int
// toField returns a field equivalent to the given reflect field.
func toField(f *reflect.StructField) field {
return f.Index
}
// invalidField is an invalid field identifier.
var invalidField = field(nil)
// IsValid reports whether the field identifier is valid.
func (f field) IsValid() bool { return f != nil }
// field returns the given field in the struct as a reflect value.
func structPointer_field(p structPointer, f field) reflect.Value {
// Special case: an extension map entry with a value of type T
// passes a *T to the struct-handling code with a zero field,
// expecting that it will be treated as equivalent to *struct{ X T },
// which has the same memory layout. We have to handle that case
// specially, because reflect will panic if we call FieldByIndex on a
// non-struct.
if f == nil {
return p.v.Elem()
}
return p.v.Elem().FieldByIndex(f)
}
// ifield returns the given field in the struct as an interface value.
func structPointer_ifield(p structPointer, f field) interface{} {
return structPointer_field(p, f).Addr().Interface()
}
// Bytes returns the address of a []byte field in the struct.
func structPointer_Bytes(p structPointer, f field) *[]byte {
return structPointer_ifield(p, f).(*[]byte)
}
// BytesSlice returns the address of a [][]byte field in the struct.
func structPointer_BytesSlice(p structPointer, f field) *[][]byte {
return structPointer_ifield(p, f).(*[][]byte)
}
// Bool returns the address of a *bool field in the struct.
func structPointer_Bool(p structPointer, f field) **bool {
return structPointer_ifield(p, f).(**bool)
}
// BoolSlice returns the address of a []bool field in the struct.
func structPointer_BoolSlice(p structPointer, f field) *[]bool {
return structPointer_ifield(p, f).(*[]bool)
}
// String returns the address of a *string field in the struct.
func structPointer_String(p structPointer, f field) **string {
return structPointer_ifield(p, f).(**string)
}
// StringSlice returns the address of a []string field in the struct.
func structPointer_StringSlice(p structPointer, f field) *[]string {
return structPointer_ifield(p, f).(*[]string)
}
// ExtMap returns the address of an extension map field in the struct.
func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
return structPointer_ifield(p, f).(*map[int32]Extension)
}
// SetStructPointer writes a *struct field in the struct.
func structPointer_SetStructPointer(p structPointer, f field, q structPointer) {
structPointer_field(p, f).Set(q.v)
}
// GetStructPointer reads a *struct field in the struct.
func structPointer_GetStructPointer(p structPointer, f field) structPointer {
return structPointer{structPointer_field(p, f)}
}
// StructPointerSlice the address of a []*struct field in the struct.
func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice {
return structPointerSlice{structPointer_field(p, f)}
}
// A structPointerSlice represents the address of a slice of pointers to structs
// (themselves messages or groups). That is, v.Type() is *[]*struct{...}.
type structPointerSlice struct {
v reflect.Value
}
func (p structPointerSlice) Len() int { return p.v.Len() }
func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} }
func (p structPointerSlice) Append(q structPointer) {
p.v.Set(reflect.Append(p.v, q.v))
}
var (
int32Type = reflect.TypeOf(int32(0))
uint32Type = reflect.TypeOf(uint32(0))
float32Type = reflect.TypeOf(float32(0))
int64Type = reflect.TypeOf(int64(0))
uint64Type = reflect.TypeOf(uint64(0))
float64Type = reflect.TypeOf(float64(0))
)
// A word32 represents a field of type *int32, *uint32, *float32, or *enum.
// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable.
type word32 struct {
v reflect.Value
}
// IsNil reports whether p is nil.
func word32_IsNil(p word32) bool {
return p.v.IsNil()
}
// Set sets p to point at a newly allocated word with bits set to x.
func word32_Set(p word32, o *Buffer, x uint32) {
t := p.v.Type().Elem()
switch t {
case int32Type:
if len(o.int32s) == 0 {
o.int32s = make([]int32, uint32PoolSize)
}
o.int32s[0] = int32(x)
p.v.Set(reflect.ValueOf(&o.int32s[0]))
o.int32s = o.int32s[1:]
return
case uint32Type:
if len(o.uint32s) == 0 {
o.uint32s = make([]uint32, uint32PoolSize)
}
o.uint32s[0] = x
p.v.Set(reflect.ValueOf(&o.uint32s[0]))
o.uint32s = o.uint32s[1:]
return
case float32Type:
if len(o.float32s) == 0 {
o.float32s = make([]float32, uint32PoolSize)
}
o.float32s[0] = math.Float32frombits(x)
p.v.Set(reflect.ValueOf(&o.float32s[0]))
o.float32s = o.float32s[1:]
return
}
// must be enum
p.v.Set(reflect.New(t))
p.v.Elem().SetInt(int64(int32(x)))
}
// Get gets the bits pointed at by p, as a uint32.
func word32_Get(p word32) uint32 {
elem := p.v.Elem()
switch elem.Kind() {
case reflect.Int32:
return uint32(elem.Int())
case reflect.Uint32:
return uint32(elem.Uint())
case reflect.Float32:
return math.Float32bits(float32(elem.Float()))
}
panic("unreachable")
}
// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct.
func structPointer_Word32(p structPointer, f field) word32 {
return word32{structPointer_field(p, f)}
}
// A word32Slice is a slice of 32-bit values.
// That is, v.Type() is []int32, []uint32, []float32, or []enum.
type word32Slice struct {
v reflect.Value
}
func (p word32Slice) Append(x uint32) {
n, m := p.v.Len(), p.v.Cap()
if n < m {
p.v.SetLen(n + 1)
} else {
t := p.v.Type().Elem()
p.v.Set(reflect.Append(p.v, reflect.Zero(t)))
}
elem := p.v.Index(n)
switch elem.Kind() {
case reflect.Int32:
elem.SetInt(int64(int32(x)))
case reflect.Uint32:
elem.SetUint(uint64(x))
case reflect.Float32:
elem.SetFloat(float64(math.Float32frombits(x)))
}
}
func (p word32Slice) Len() int {
return p.v.Len()
}
func (p word32Slice) Index(i int) uint32 {
elem := p.v.Index(i)
switch elem.Kind() {
case reflect.Int32:
return uint32(elem.Int())
case reflect.Uint32:
return uint32(elem.Uint())
case reflect.Float32:
return math.Float32bits(float32(elem.Float()))
}
panic("unreachable")
}
// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct.
func structPointer_Word32Slice(p structPointer, f field) word32Slice {
return word32Slice{structPointer_field(p, f)}
}
// word64 is like word32 but for 64-bit values.
type word64 struct {
v reflect.Value
}
func word64_Set(p word64, o *Buffer, x uint64) {
t := p.v.Type().Elem()
switch t {
case int64Type:
if len(o.int64s) == 0 {
o.int64s = make([]int64, uint64PoolSize)
}
o.int64s[0] = int64(x)
p.v.Set(reflect.ValueOf(&o.int64s[0]))
o.int64s = o.int64s[1:]
return
case uint64Type:
if len(o.uint64s) == 0 {
o.uint64s = make([]uint64, uint64PoolSize)
}
o.uint64s[0] = x
p.v.Set(reflect.ValueOf(&o.uint64s[0]))
o.uint64s = o.uint64s[1:]
return
case float64Type:
if len(o.float64s) == 0 {
o.float64s = make([]float64, uint64PoolSize)
}
o.float64s[0] = math.Float64frombits(x)
p.v.Set(reflect.ValueOf(&o.float64s[0]))
o.float64s = o.float64s[1:]
return
}
panic("unreachable")
}
func word64_IsNil(p word64) bool {
return p.v.IsNil()
}
func word64_Get(p word64) uint64 {
elem := p.v.Elem()
switch elem.Kind() {
case reflect.Int64:
return uint64(elem.Int())
case reflect.Uint64:
return elem.Uint()
case reflect.Float64:
return math.Float64bits(elem.Float())
}
panic("unreachable")
}
func structPointer_Word64(p structPointer, f field) word64 {
return word64{structPointer_field(p, f)}
}
type word64Slice struct {
v reflect.Value
}
func (p word64Slice) Append(x uint64) {
n, m := p.v.Len(), p.v.Cap()
if n < m {
p.v.SetLen(n + 1)
} else {
t := p.v.Type().Elem()
p.v.Set(reflect.Append(p.v, reflect.Zero(t)))
}
elem := p.v.Index(n)
switch elem.Kind() {
case reflect.Int64:
elem.SetInt(int64(int64(x)))
case reflect.Uint64:
elem.SetUint(uint64(x))
case reflect.Float64:
elem.SetFloat(float64(math.Float64frombits(x)))
}
}
func (p word64Slice) Len() int {
return p.v.Len()
}
func (p word64Slice) Index(i int) uint64 {
elem := p.v.Index(i)
switch elem.Kind() {
case reflect.Int64:
return uint64(elem.Int())
case reflect.Uint64:
return uint64(elem.Uint())
case reflect.Float64:
return math.Float64bits(float64(elem.Float()))
}
panic("unreachable")
}
func structPointer_Word64Slice(p structPointer, f field) word64Slice {
return word64Slice{structPointer_field(p, f)}
}
| 1067282423-goproto000 | proto/pointer_reflect.go | Go | bsd | 11,339 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class Schema implements Serializable {
private static final long serialVersionUID = -6086978758296528123L;
Schema() {}
/**
* schema name
*/
private String tableSchem;
/**
* catalog name (may be null)
*/
private String tableCatalog;
String getTableSchem() {
return tableSchem;
}
void setTableSchem( String tableSchem ) {
this.tableSchem = tableSchem;
}
String getTableCatalog() {
return tableCatalog;
}
void setTableCatalog( String tableCatalog ) {
this.tableCatalog = tableCatalog;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/Schema.java | Java | asf20 | 674 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class Column implements Serializable {
private static final long serialVersionUID = 4257926755376078999L;
Column() {
}
/**
* table catalog (may be null)
*/
private String tableCat;
/**
* table schema (may be null)
*/
private String tableSchem;
/**
* table name
*/
private String tableName;
/**
* column name
*/
private String columnName;
/**
* SQL type from java.sql.Types
*/
private int dataType;
/**
* Data source dependent type name, for a UDT the type name is fully qualified
*/
private String typeName;
/**
* column size
*/
private int columnSize;
/**
* the number of fractional digits. Null is returned for data types where DECIMAL_DIGITS is not
* applicable.
*/
private int decimalDigits;
/**
* Radix (typically either 10 or 2)
*/
private int numPrecRadix;
/**
* is NULL allowed columnNoNulls - might not allow NULL values columnNullable - definitely
* allows NULL values columnNullableUnknown - nullability unknown
*/
private int nullable;
/**
* comment describing column (may be null)
*/
private String remarks;
/**
* efault value for the column, which should be interpreted as a string when the value is
* enclosed in single quotes (may be null)
*/
private String columnDef;
/**
* for char types the maximum number of bytes in the column
*/
private int charOctetLength;
/**
* index of column in table (starting at 1)
*/
private int originalPosition;
/**
* ISO rules are used to determine the nullability for a column. YES --- if the parameter can
* include NULLs NO --- if the parameter cannot include NULLs empty string --- if the
* nullability for the parameter is unknown
*/
private String isNullable;
/**
* catalog of table that is the scope of a reference attribute (null if DATA_TYPE isn't REF)
*/
private String scopeCatlog;
/**
* schema of table that is the scope of a reference attribute (null if the DATA_TYPE isn't REF)
*/
private String scopeSchema;
/**
* table name that this the scope of a reference attribure (null if the DATA_TYPE isn't REF)
*/
private String scopeTable;
/**
* source type of a distinct type or user-generated Ref type, SQL type from java.sql.Types (null
* if DATA_TYPE isn't DISTINCT or user-generated REF)
*/
private short sourceDataType;
/**
* Indicates whether this column is auto incremented YES --- if the column is auto incremented
* NO --- if the column is not auto incremented empty string --- if it cannot be determined
* whether the column is auto incremented parameter is unknown
*/
private String isAutoincrement;
String getTableCat() {
return tableCat;
}
void setTableCat( String tableCat ) {
this.tableCat = tableCat;
}
String getTableSchem() {
return tableSchem;
}
void setTableSchem( String tableSchem ) {
this.tableSchem = tableSchem;
}
String getTableName() {
return tableName;
}
void setTableName( String tableName ) {
this.tableName = tableName;
}
String getColumnName() {
return columnName;
}
void setColumnName( String columnName ) {
this.columnName = columnName;
}
int getDataType() {
return dataType;
}
void setDataType( int dataType ) {
this.dataType = dataType;
}
String getTypeName() {
return typeName;
}
void setTypeName( String typeName ) {
this.typeName = typeName;
}
int getColumnSize() {
return columnSize;
}
void setColumnSize( int columnSize ) {
this.columnSize = columnSize;
}
int getDecimalDigits() {
return decimalDigits;
}
void setDecimalDigits( int decimalDigits ) {
this.decimalDigits = decimalDigits;
}
int getNumPrecRadix() {
return numPrecRadix;
}
void setNumPrecRadix( int numPrecRadix ) {
this.numPrecRadix = numPrecRadix;
}
int getNullable() {
return nullable;
}
void setNullable( int nullable ) {
this.nullable = nullable;
}
String getRemarks() {
return remarks;
}
void setRemarks( String remarks ) {
this.remarks = remarks;
}
String getColumnDef() {
return columnDef;
}
void setColumnDef( String columnDef ) {
this.columnDef = columnDef;
}
int getCharOctetLength() {
return charOctetLength;
}
void setCharOctetLength( int charOctetLength ) {
this.charOctetLength = charOctetLength;
}
int getOriginalPosition() {
return originalPosition;
}
void setOriginalPosition( int originalPosition ) {
this.originalPosition = originalPosition;
}
String getIsNullable() {
return isNullable;
}
void setIsNullable( String isNullable ) {
this.isNullable = isNullable;
}
String getScopeCatlog() {
return scopeCatlog;
}
void setScopeCatlog( String scopeCatlog ) {
this.scopeCatlog = scopeCatlog;
}
String getScopeSchema() {
return scopeSchema;
}
void setScopeSchema( String scopeSchema ) {
this.scopeSchema = scopeSchema;
}
String getScopeTable() {
return scopeTable;
}
void setScopeTable( String scopeTable ) {
this.scopeTable = scopeTable;
}
short getSourceDataType() {
return sourceDataType;
}
void setSourceDataType( short sourceDataType ) {
this.sourceDataType = sourceDataType;
}
String getIsAutoincrement() {
return isAutoincrement;
}
void setIsAutoincrement( String isAutoincrement ) {
this.isAutoincrement = isAutoincrement;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/Column.java | Java | asf20 | 6,377 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class FunctionColumn implements Serializable {
private static final long serialVersionUID = 2416865956602345916L;
FunctionColumn() {
}
/**
* function catalog (may be null)
*/
private String functionCat;
/**
* function schema (may be null)
*/
private String functionSchem;
/**
* function name. This is the name used to invoke the function
*/
private String functionName;
/**
* column/parameter name
*/
private String columnName;
/**
* kind of column/parameter: functionColumnUnknown - nobody knows
* functionColumnIn - IN parameter functionColumnInOut - INOUT parameter
* functionColumnOut - OUT parameter functionColumnReturn - function return
* value functionColumnResult - Indicates that the parameter or column is a
* column in the ResultSet
*/
private short columnType;
/**
* SQL type from java.sql.Types
*/
private int dataType;
/**
* SQL type name, for a UDT type the type name is fully qualified
*/
private String typeName;
/**
* precision
*/
private int precision;
/**
* length in bytes of data
*/
private int length;
/**
* scale - null is returned for data types where SCALE is not applicable.
*/
private short scale;
/**
* radix
*/
private short radix;
/**
* can it contain NULL. functionNoNulls - does not allow NULL values
* functionNullable - allows NULL values functionNullableUnknown -
* nullability unknown
*/
private short nullable;
/**
* comment describing column/parameter
*/
private String remarks;
/**
* the maximum length of binary and character based parameters or columns.
* For any other datatype the returned value is a NULL
*/
private int charOctetLength;
/**
* the ordinal position, starting from 1, for the input and output
* parameters. A value of 0 is returned if this row describes the function's
* return value. For result set columns, it is the ordinal position of the
* column in the result set starting from 1.
*/
private int ordinalPosition;
/**
* ISO rules are used to determine the nullability for a parameter or
* column. YES --- if the parameter or column can include NULLs NO --- if
* the parameter or column cannot include NULLs empty string --- if the
* nullability for the parameter or column is unknown
*/
private String isNullable;
/**
* the name which uniquely identifies this function within its schema. This
* is a user specified, or DBMS generated, name that may be different then
* the FUNCTION_NAME for example with overload functions
*/
private String specificName;
String getFunctionCat() {
return functionCat;
}
void setFunctionCat(String functionCat) {
this.functionCat = functionCat;
}
String getFunctionSchem() {
return functionSchem;
}
void setFunctionSchem(String functionSchem) {
this.functionSchem = functionSchem;
}
String getFunctionName() {
return functionName;
}
void setFunctionName(String functionName) {
this.functionName = functionName;
}
String getColumnName() {
return columnName;
}
void setColumnName(String columnName) {
this.columnName = columnName;
}
short getColumnType() {
return columnType;
}
void setColumnType(short columnType) {
this.columnType = columnType;
}
int getDataType() {
return dataType;
}
void setDataType(int dataType) {
this.dataType = dataType;
}
String getTypeName() {
return typeName;
}
void setTypeName(String typeName) {
this.typeName = typeName;
}
int getPrecision() {
return precision;
}
void setPrecision(int precision) {
this.precision = precision;
}
int getLength() {
return length;
}
void setLength(int length) {
this.length = length;
}
short getScale() {
return scale;
}
void setScale(short scale) {
this.scale = scale;
}
short getRadix() {
return radix;
}
void setRadix(short radix) {
this.radix = radix;
}
short getNullable() {
return nullable;
}
void setNullable(short nullable) {
this.nullable = nullable;
}
String getRemarks() {
return remarks;
}
void setRemarks(String remarks) {
this.remarks = remarks;
}
int getCharOctetLength() {
return charOctetLength;
}
void setCharOctetLength(int charOctetLength) {
this.charOctetLength = charOctetLength;
}
int getOrdinalPosition() {
return ordinalPosition;
}
void setOrdinalPosition(int ordinalPosition) {
this.ordinalPosition = ordinalPosition;
}
String getIsNullable() {
return isNullable;
}
void setIsNullable(String isNullable) {
this.isNullable = isNullable;
}
String getSpecificName() {
return specificName;
}
void setSpecificName(String specificName) {
this.specificName = specificName;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/FunctionColumn.java | Java | asf20 | 4,983 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
import java.sql.RowIdLifetime;
public class Database implements Serializable {
private static final long serialVersionUID = -1225713110410721872L;
/**
* Retrieves whether the current user can call all the procedures returned by the method
* getProcedures.
*/
private boolean allProceduresAreCallable;
/**
* Retrieves whether the current user can use all the tables returned by the method getTables in
* a SELECT statement.
*/
private boolean allTablesAreSelectable;
/**
* Retrieves whether a SQLException while autoCommit is true inidcates that all open ResultSets
* are closed, even ones that are holdable. When a SQLException occurs while autocommit is true,
* it is vendor specific whether the JDBC driver responds with a commit operation, a rollback
* operation, or by doing neither a commit nor a rollback. A potential result of this difference
* is in whether or not holdable ResultSets are closed.
*/
private boolean autoCommitFailureClosesAllResultSets;
/**
* Retrieves whether a data definition statement within a transaction forces the transaction to
* commit
*/
private boolean dataDefinitionCausesTransactionCommit;
/**
* Retrieves whether this database ignores a data definition statement within a transaction
*/
private boolean dataDefinitionIgnoredInTransactions;
/**
* Retrieves whether or not a visible row delete can be detected by calling the method
* ResultSet.rowDeleted. If the method deletesAreDetected returns false, it means that deleted
* rows are removed from the result set
*/
private boolean deletesAreDetected;
/**
* Retrieves whether the return value for the method getMaxRowSize includes the SQL data types
* LONGVARCHAR and LONGVARBINARY
*/
private boolean doesMaxRowSizeIncludeBlobs;
/**
* Retrieves the String that this database uses as the separator between a catalog and table
* name
*/
private String catalogSeparator;
/**
* Retrieves the database vendor's preferred term for "catalog".
*/
private String catalogTerm;
/**
* Retrieves the major version number of the underlying database.
*/
private int databaseMajorVersion;
/**
* Retrieves the minor version number of the underlying database.
*/
private int databaseMinorVersion;
/**
* Retrieves the name of this database product.
*/
private String databaseProductName;
/**
* Retrieves the version number of this database product.
*/
private String databaseProductVersion;
/**
* Retrieves this database's default transaction isolation level. The possible values are
* defined in java.sql.Connection
*/
private int defaultTransactionIsolation;
/**
* Retrieves this JDBC driver's major version number.
*/
private int driverMajorVersion;
/**
* Retrieves this JDBC driver's minor version number
*/
private int driverMinorVersion;
/**
* Retrieves the name of this JDBC driver
*/
private String driverName;
/**
* Retrieves the version number of this JDBC driver as a String.
*/
private String driverVersion;
/**
* Retrieves all the "extra" characters that can be used in unquoted identifier names (those
* beyond a-z, A-Z, 0-9 and _)
*/
private String extraNameCharacters;
/**
* Retrieves the string used to quote SQL identifiers. This method returns a space " " if
* identifier quoting is not supported
*/
private String identifierQuoteString;
/**
* Retrieves the major JDBC version number for this driver
*/
private int jdbcMajorVersion;
/**
* Retrieves the minor JDBC version number for this driver
*/
private int jdbcMinorVersion;
/**
* Retrieves the maximum number of hex characters this database allows in an inline binary
* literal
*/
private int maxBinaryLiteralLength;
/**
* Retrieves the maximum number of characters that this database allows in a catalog name
*/
private int maxCatalogNameLength;
/**
* Retrieves the maximum number of characters this database allows for a character literal.
*/
private int maxCharLiteralLength;
/**
* Retrieves the maximum number of characters this database allows for a column name.
*/
private int maxColumnNameLength;
/**
* Retrieves the maximum number of columns this database allows in a GROUP BY clause.
*/
private int maxColumnsInGroupBy;
/**
* Retrieves the maximum number of columns this database allows in an index.
*/
private int maxColumnsInIndex;
/**
* Retrieves the maximum number of columns this database allows in an ORDER BY clause.
*/
private int maxColumnsInOrderBy;
/**
* Retrieves the maximum number of columns this database allows in a SELECT list.
*/
private int maxColumnsInSelect;
/**
* Retrieves the maximum number of columns this database allows in a table.
*/
private int maxColumnsInTable;
/**
* Retrieves the maximum number of concurrent connections to this database that are possible.
*/
private int maxConnections;
/**
* Retrieves the maximum number of characters that this database allows in a cursor name.
*/
private int maxCursorNameLength;
/**
* Retrieves the maximum number of bytes this database allows for an index, including all of the
* parts of the index.
*/
private int maxIndexLength;
/**
* Retrieves the maximum number of characters that this database allows in a procedure name.
*/
private int maxProcedureNameLength;
/**
* Retrieves the maximum number of bytes this database allows in a single row.
*/
private int maxRowSize;
/**
* Retrieves the maximum number of characters that this database allows in a schema name.
*/
private int maxSchemaNameLength;
/**
* Retrieves the maximum number of characters this database allows in an SQL statement.
*/
private int maxStatementLength;
/**
* Retrieves the maximum number of active statements to this database that can be open at the
* same time.
*/
private int maxStatements;
/**
* Retrieves the maximum number of characters this database allows in a table name.
*/
private int maxTableNameLength;
/**
* Retrieves the maximum number of tables this database allows in a SELECT statement.
*/
private int maxTablesInSelect;
/**
* Retrieves the maximum number of characters this database allows in a user name.
*/
private int maxUserNameLength;
/**
* Retrieves a comma-separated list of math functions available with this database. These are
* the Open /Open CLI math function names used in the JDBC function escape clause.
*/
private String numericFunctions;
/**
* Retrieves the database vendor's preferred term for "procedure".
*/
private String procedureTerm;
/**
* Retrieves this database's default holdability for ResultSet objects.
*/
private int resultSetHoldability;
/**
* Indicates whether or not this data source supports the SQL ROWID type, and if so the lifetime
* for which a RowId object remains valid.
*/
private RowIdLifetime rowIdLifetime;
/**
* Retrieves the database vendor's preferred term for "schema".
*/
private String schemaTerm;
/**
* Retrieves the string that can be used to escape wildcard characters. This is the string that
* can be used to escape '_' or '%' in the catalog search parameters that are a pattern (and
* therefore use one of the wildcard characters).
*/
private String searchStringEscape;
/**
* Retrieves a comma-separated list of all of this database's SQL keywords that are NOT also
* SQL:2003 keywords.
*/
private String sqlKeywords;
/**
* Indicates whether the SQLSTATE returned by SQLException.getSQLState is X/Open (now known as
* Open Group) SQL CLI or SQL:2003.
*/
private int sqlStateType;
/**
* Retrieves a comma-separated list of string functions available with this database. These are
* the Open Group CLI string function names used in the JDBC function escape clause.
*/
private String stringFunctions;
/**
* Retrieves a comma-separated list of system functions available with this database. These are
* the Open Group CLI system function names used in the JDBC function escape clause.
*/
private String systemFunctions;
/**
* Retrieves a comma-separated list of the time and date functions available with this database.
*/
private String timeDateFunctions;
/**
* Retrieves the URL for this DBMS.
*/
private String url;
/**
* Retrieves the user name as known to this database.
*/
private String userName;
/**
* Retrieves whether or not a visible row insert can be detected by calling the method
* ResultSet.rowInserted.
*/
private boolean insertsAreDetected;
/**
* Retrieves whether a catalog appears at the start of a fully qualified table name. If not, the
* catalog appears at the end.
*/
private boolean isCatalogAtStart;
/**
* Retrieves whether this database is in read-only mode.
*/
private boolean isReadOnly;
/**
* Indicates whether updates made to a LOB are made on a copy or directly to the LOB.
*/
private boolean locatorsUpdateCopy;
/**
* Retrieves whether this database supports concatenations between NULL and non-NULL values
* being NULL.
*/
private boolean nullPlusNonNullIsNull;
/**
* Retrieves whether NULL values are sorted at the end regardless of sort order.
*/
private boolean nullsAreSortedAtEnd;
/**
* Retrieves whether NULL values are sorted at the start regardless of sort order.
*/
private boolean nullsAreSortedAtStart;
/**
* Retrieves whether NULL values are sorted high. Sorted high means that NULL values sort higher
* than any other value in a domain. In an ascending order, if this method returns true, NULL
* values will appear at the end. By contrast, the method nullsAreSortedAtEnd indicates whether
* NULL values are sorted at the end regardless of sort order.
*/
private boolean nullsAreSortedHigh;
/**
* Retrieves whether NULL values are sorted low. Sorted low means that NULL values sort lower
* than any other value in a domain. In an ascending order, if this method returns true, NULL
* values will appear at the beginning. By contrast, the method nullsAreSortedAtStart indicates
* whether NULL values are sorted at the beginning regardless of sort order.
*/
private boolean nullsAreSortedLow;
/**
* Retrieves whether deletes made by others are visible.
*/
private boolean othersDeletesAreVisible;
/**
* Retrieves whether inserts made by others are visible.
*/
private boolean othersInsertsAreVisible;
/**
* Retrieves whether updates made by others are visible.
*/
private boolean othersUpdatesAreVisible;
/**
* Retrieves whether a result set's own deletes are visible.
*/
private boolean ownDeletesAreVisible;
/**
* Retrieves whether a result set's own inserts are visible.
*/
private boolean ownInsertsAreVisible;
/**
* Retrieves whether for the given type of ResultSet object, the result set's own updates are
* visible.
*/
private boolean ownUpdatesAreVisible;
/**
* Retrieves whether this database treats mixed case unquoted SQL identifiers as case
* insensitive and stores them in lower case.
*/
private boolean storesLowerCaseIdentifiers;
/**
* Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive
* and stores them in lower case.
*/
private boolean storesLowerCaseQuotedIdentifiers;
/**
* Retrieves whether this database treats mixed case unquoted SQL identifiers as case
* insensitive and stores them in mixed case.
*/
private boolean storesMixedCaseIdentifiers;
/**
* Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive
* and stores them in mixed case.
*/
private boolean storesMixedCaseQuotedIdentifiers;
/**
* Retrieves whether this database treats mixed case unquoted SQL identifiers as case
* insensitive and stores them in upper case.
*/
private boolean storesUpperCaseIdentifiers;
/**
* Retrieves whether this database supports ALTER TABLE with add column.
*/
private boolean supportsAlterTableWithAddColumn;
/**
* Retrieves whether this database supports ALTER TABLE with drop column.
*/
private boolean supportsAlterTableWithDropColumn;
/**
* Retrieves whether this database supports the ANSI92 entry level SQL grammar.
*/
private boolean supportsANSI92EntryLevelSQL;
/**
* Retrieves whether this database supports the ANSI92 full SQL grammar supported.
*/
private boolean supportsANSI92FullSQL;
/**
* Retrieves whether this database supports the ANSI92 intermediate SQL grammar supported.
*/
private boolean supportsANSI92IntermediateSQL;
/**
* Retrieves whether this database supports batch updates.
*/
private boolean supportsBatchUpdates;
/**
* Retrieves whether a catalog name can be used in a data manipulation statement.
*/
private boolean supportsCatalogsInDataManipulation;
/**
* Retrieves whether a catalog name can be used in an index definition statement.
*/
private boolean supportsCatalogsInIndexDefinitions;
/**
* Retrieves whether a catalog name can be used in a privilege definition statement.
*/
private boolean supportsCatalogsInPrivilegeDefinitions;
/**
* Retrieves whether a catalog name can be used in a procedure call statement.
*/
private boolean supportsCatalogsInProcedureCalls;
/**
* Retrieves whether a catalog name can be used in a table definition statement.
*/
private boolean supportsCatalogsInTableDefinitions;
/**
* Retrieves whether this database supports column aliasing.
*/
private boolean supportsColumnAliasing;
/**
* Retrieves whether this database supports the JDBC scalar function CONVERT for the conversion
* of one JDBC type to another. The JDBC types are the generic SQL data types defined in
* java.sql.Types.
*/
private boolean supportsConvert;
/**
*
*/
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/Database.java | Java | asf20 | 16,420 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class ProcedureColumn implements Serializable {
private static final long serialVersionUID = 1886695116931613838L;
ProcedureColumn() {
}
/**
* procedure catalog (may be null)
*/
private String procedureCat;
/**
* procedure schema (may be null)
*/
private String procedureSchem;
/**
* procedure name
*/
private String procedureName;
/**
* column/parameter name
*/
private String columnName;
/**
* kind of column/parameter:
* procedureColumnUnknown - nobody knows
* procedureColumnIn - IN parameter
* procedureColumnInOut - INOUT parameter
* procedureColumnOut - OUT parameter
* procedureColumnReturn - procedure return value
* procedureColumnResult - result column in ResultSet
*/
private short columnType;
/**
* SQL type from java.sql.Types
*/
private int dataType;
/**
* SQL type name, for a UDT type the type name is fully qualified
*/
private String typeName;
/**
* precision
*/
private int precision;
/**
* length in bytes of data
*/
private int length;
/**
* scale - null is returned for data types where SCALE is not applicable
*/
private short scale;
/**
* radix
*/
private short radix;
/**
* can it contain NULL.
* procedureNoNulls - does not allow NULL values
* procedureNullable - allows NULL values
* procedureNullableUnknown - nullability unknown
*/
private short nullable;
/**
* comment describing parameter/column
*/
private String remarks;
/**
* default value for the column, which should be interpreted as a string when the value is enclosed in single quotes (may be null)
* The string NULL (not enclosed in quotes) - if NULL was specified as the default value
* TRUNCATE (not enclosed in quotes) - if the specified default value cannot be represented without truncation
* NULL - if a default value was not specified
*/
private String columnDef;
/**
* reserved for future use
*/
private int sqlDataType;
/**
* reserved for future use
*/
private int sqlDatetimeSub;
/**
* the maximum length of binary and character based columns. For any other datatype the returned value is a NULL
*/
private int charOctetLength;
/**
* the ordinal position, starting from 1, for the input and output parameters for a procedure. A value of 0 is returned if this row describes the procedure's return value. For result set columns, it is the ordinal position of the column in the result set starting from 1. If there are multiple result sets, the column ordinal positions are implementation defined.
*/
private int ordinalPosition;
/**
* ISO rules are used to determine the nullability for a column.
* YES --- if the parameter can include NULLs
* NO --- if the parameter cannot include NULLs
* empty string --- if the nullability for the parameter is unknown
*/
private String isNullable;
/**
* the name which uniquely identifies this procedure within its schema.
*/
private String specificName;
String getProcedureCat() {
return procedureCat;
}
void setProcedureCat( String procedureCat ) {
this.procedureCat = procedureCat;
}
String getProcedureSchem() {
return procedureSchem;
}
void setProcedureSchem( String procedureSchem ) {
this.procedureSchem = procedureSchem;
}
String getProcedureName() {
return procedureName;
}
void setProcedureName( String procedureName ) {
this.procedureName = procedureName;
}
String getColumnName() {
return columnName;
}
void setColumnName( String columnName ) {
this.columnName = columnName;
}
short getColumnType() {
return columnType;
}
void setColumnType( short columnType ) {
this.columnType = columnType;
}
int getDataType() {
return dataType;
}
void setDataType( int dataType ) {
this.dataType = dataType;
}
String getTypeName() {
return typeName;
}
void setTypeName( String typeName ) {
this.typeName = typeName;
}
int getPrecision() {
return precision;
}
void setPrecision( int precision ) {
this.precision = precision;
}
int getLength() {
return length;
}
void setLength( int length ) {
this.length = length;
}
short getScale() {
return scale;
}
void setScale( short scale ) {
this.scale = scale;
}
short getRadix() {
return radix;
}
void setRadix( short radix ) {
this.radix = radix;
}
short getNullable() {
return nullable;
}
void setNullable( short nullable ) {
this.nullable = nullable;
}
String getRemarks() {
return remarks;
}
void setRemarks( String remarks ) {
this.remarks = remarks;
}
String getColumnDef() {
return columnDef;
}
void setColumnDef( String columnDef ) {
this.columnDef = columnDef;
}
int getSqlDataType() {
return sqlDataType;
}
void setSqlDataType( int sqlDataType ) {
this.sqlDataType = sqlDataType;
}
int getSqlDatetimeSub() {
return sqlDatetimeSub;
}
void setSqlDatetimeSub( int sqlDatetimeSub ) {
this.sqlDatetimeSub = sqlDatetimeSub;
}
int getCharOctetLength() {
return charOctetLength;
}
void setCharOctetLength( int charOctetLength ) {
this.charOctetLength = charOctetLength;
}
int getOrdinalPosition() {
return ordinalPosition;
}
void setOrdinalPosition( int ordinalPosition ) {
this.ordinalPosition = ordinalPosition;
}
String getIsNullable() {
return isNullable;
}
void setIsNullable( String isNullable ) {
this.isNullable = isNullable;
}
String getSpecificName() {
return specificName;
}
void setSpecificName( String specificName ) {
this.specificName = specificName;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/ProcedureColumn.java | Java | asf20 | 6,142 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class ClientInfoProperty implements Serializable {
private static final long serialVersionUID = 2238063041885637942L;
ClientInfoProperty() {
}
/**
* The name of the client info property
*/
private String name;
/**
* The maximum length of the value for the property
*/
private int maxLen;
/**
* The default value of the property
*/
private String defaultValue;
/**
* A description of the property. This will typically contain information as to where this property is stored in the database.
*/
private String description;
String getName() {
return name;
}
void setName( String name ) {
this.name = name;
}
int getMaxLen() {
return maxLen;
}
void setMaxLen( int maxLen ) {
this.maxLen = maxLen;
}
String getDefaultValue() {
return defaultValue;
}
void setDefaultValue( String defaultValue ) {
this.defaultValue = defaultValue;
}
String getDescription() {
return description;
}
void setDescription( String description ) {
this.description = description;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/ClientInfoProperty.java | Java | asf20 | 1,226 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class Table implements Serializable {
private static final long serialVersionUID = 3363512786615751411L;
/**
* table catalog (may be null)
*/
private String tableCat;
/**
* table schema (may be null)
*/
private String tableSchem;
/**
* table name
*/
private String tableName;
/**
* table type. Typical types are "TABLE", "VIEW", "SYSTEM TABLE",
* "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM"
*/
private TableType tableType;
/**
* explanatory comment on the table
*/
private String remarks;
/**
* the types catalog (may be null)
*/
private String typeCat;
String getTableCat() {
return tableCat;
}
void setTableCat(String tableCat) {
this.tableCat = tableCat;
}
String getTableSchem() {
return tableSchem;
}
void setTableSchem(String tableSchem) {
this.tableSchem = tableSchem;
}
String getTableName() {
return tableName;
}
void setTableName(String tableName) {
this.tableName = tableName;
}
TableType getTableType() {
return tableType;
}
void setTableType(TableType tableType) {
this.tableType = tableType;
}
String getRemarks() {
return remarks;
}
void setRemarks(String remarks) {
this.remarks = remarks;
}
String getTypeCat() {
return typeCat;
}
void setTypeCat(String typeCat) {
this.typeCat = typeCat;
}
String getTypeSchem() {
return typeSchem;
}
void setTypeSchem(String typeSchem) {
this.typeSchem = typeSchem;
}
String getTypeName() {
return typeName;
}
void setTypeName(String typeName) {
this.typeName = typeName;
}
String getSelfReferencingColName() {
return selfReferencingColName;
}
void setSelfReferencingColName(String selfReferencingColName) {
this.selfReferencingColName = selfReferencingColName;
}
String getRefGeneration() {
return refGeneration;
}
void setRefGeneration(String refGeneration) {
this.refGeneration = refGeneration;
}
/**
* the types schema (may be null)
*/
private String typeSchem;
/**
* type name (may be null)
*/
private String typeName;
/**
* name of the designated "identifier" column of a typed table (may be null)
*/
private String selfReferencingColName;
/**
* specifies how values in SELF_REFERENCING_COL_NAME are created. Values are
* "SYSTEM", "USER", "DERIVED". (may be null)
*/
private String refGeneration;
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/Table.java | Java | asf20 | 2,558 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class TableType implements Serializable {
private static final long serialVersionUID = 4214894369464157382L;
static final TableType table_type_table = new TableType( "TABLE" );
static final TableType table_type_view = new TableType( "VIEW" );
static final TableType table_type_system_table = new TableType( "SYSTEM TABLE" );
static final TableType table_type_global_temporary = new TableType( "GLOBAL TEMPORARY" );
static final TableType table_type_local_temporary = new TableType( "LOCAL TEMPORARY" );
static final TableType table_type_alias = new TableType( "ALIAS" );
static final TableType table_type_synonym = new TableType( "SYNONYM" );
TableType ( String tableType ) {
this.tableType = tableType;
}
private String tableType;
String getTableType() {
return tableType;
}
void setTableType(String tableType) {
this.tableType = tableType;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/TableType.java | Java | asf20 | 991 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class ColumnPrivilege implements Serializable {
private static final long serialVersionUID = 8532093440653495540L;
ColumnPrivilege() {
}
/**
* table catalog (may be null)
*/
private String tableCat;
/**
* table schema (may be null)
*/
private String tableSchem;
/**
* table name
*/
private String tableName;
/**
* column name
*/
private String columnName;
/**
* grantor of access (may be null)
*/
private String grantor;
/**
* grantee of access
*/
private String grantee;
/**
* name of access (SELECT, INSERT, UPDATE, REFRENCES, ...)
*/
private String privilege;
/**
* "YES" if grantee is permitted to grant to others; "NO" if not; null if unknown
*/
private String isGrantable;
String getTableCat() {
return tableCat;
}
void setTableCat( String tableCat ) {
this.tableCat = tableCat;
}
String getTableSchem() {
return tableSchem;
}
void setTableSchem( String tableSchem ) {
this.tableSchem = tableSchem;
}
String getTableName() {
return tableName;
}
void setTableName( String tableName ) {
this.tableName = tableName;
}
String getColumnName() {
return columnName;
}
void setColumnName( String columnName ) {
this.columnName = columnName;
}
String getGrantor() {
return grantor;
}
void setGrantor( String grantor ) {
this.grantor = grantor;
}
String getGrantee() {
return grantee;
}
void setGrantee( String grantee ) {
this.grantee = grantee;
}
String getPrivilege() {
return privilege;
}
void setPrivilege( String privilege ) {
this.privilege = privilege;
}
String getIsGrantable() {
return isGrantable;
}
void setIsGrantable( String isGrantable ) {
this.isGrantable = isGrantable;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/ColumnPrivilege.java | Java | asf20 | 2,214 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class Function implements Serializable {
private static final long serialVersionUID = 7337130883767894365L;
Function() {
}
/**
* function catalog (may be null)
*/
private String functionCat;
/**
* function schema (may be null)
*/
private String functionSchema;
/**
* function name. This is the name used to invoke the function
*/
private String functionName;
/**
* explanatory comment on the function
*/
private String remarks;
/**
* kind of function: functionResultUnknown - Cannot determine if a return
* value or table will be returned functionNoTable- Does not return a table
* functionReturnsTable - Returns a table
*/
private short functionType;
/**
* the name which uniquely identifies this function within its schema. This
* is a user specified, or DBMS generated, name that may be different then
* the FUNCTION_NAME for example with overload functions
*/
private String specificName;
String getFunctionCat() {
return functionCat;
}
void setFunctionCat(String functionCat) {
this.functionCat = functionCat;
}
String getFunctionSchema() {
return functionSchema;
}
void setFunctionSchema(String functionSchema) {
this.functionSchema = functionSchema;
}
String getFunctionName() {
return functionName;
}
void setFunctionName(String functionName) {
this.functionName = functionName;
}
String getRemarks() {
return remarks;
}
void setRemarks(String remarks) {
this.remarks = remarks;
}
short getFunctionType() {
return functionType;
}
void setFunctionType(short functionType) {
this.functionType = functionType;
}
String getSpecificName() {
return specificName;
}
void setSpecificName(String specificName) {
this.specificName = specificName;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/Function.java | Java | asf20 | 1,935 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class Procedure implements Serializable {
private static final long serialVersionUID = -4039205106133212013L;
/**
* procedure catalog (may be null)
*/
private String procedureCat;
/**
* procedure schema (may be null)
*/
private String procedureSchem;
/**
* procedure name
*/
private String procedureName;
/**
* explanatory comment on the procedure
*/
private String remarks;
/**
* kind of procedure:
* procedureResultUnknown - Cannot determine if a return value will be returned
* procedureNoResult - Does not return a return value
* procedureReturnsResult - Returns a return value
*/
private short procedureType;
/**
* The name which uniquely identifies this procedure within its schema.
*/
private String specificName;
String getProcedureCat() {
return procedureCat;
}
void setProcedureCat( String procedureCat ) {
this.procedureCat = procedureCat;
}
String getProcedureSchem() {
return procedureSchem;
}
void setProcedureSchem( String procedureSchem ) {
this.procedureSchem = procedureSchem;
}
String getProcedureName() {
return procedureName;
}
void setProcedureName( String procedureName ) {
this.procedureName = procedureName;
}
String getRemarks() {
return remarks;
}
void setRemarks( String remarks ) {
this.remarks = remarks;
}
short getProcedureType() {
return procedureType;
}
void setProcedureType( short procedureType ) {
this.procedureType = procedureType;
}
String getSpecificName() {
return specificName;
}
void setSpecificName( String specificName ) {
this.specificName = specificName;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/Procedure.java | Java | asf20 | 1,865 |
package com.xyz.practice.jdbc.databasemetadata;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.List;
public class DatabaseMetaDataAccess {
private DatabaseMetaData dmd;
public DatabaseMetaDataAccess( DatabaseMetaData dmd ) {
this.dmd = dmd;
}
public Database getDatabase() throws SQLException {
Database db = new Database();
return db;
}
public List< ReferenceKey > getCrossReference( String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable ) throws SQLException {
List< ReferenceKey > referenceKeys = Converter.convertReferenceKeys( dmd.getCrossReference( parentCatalog, parentSchema, parentTable, foreignCatalog, foreignSchema, foreignTable ) );
return referenceKeys;
}
public List< ColumnPrivilege > getColumnPrivileges( String catalog, String schema, String table, String columnNamePattern ) throws SQLException {
List< ColumnPrivilege > columnPrivileges = Converter.convertColumnPrivileges( dmd.getColumnPrivileges( catalog, schema, table, columnNamePattern ) );
return columnPrivileges;
}
public List< ClientInfoProperty > getClientInfoProperties() throws SQLException {
List< ClientInfoProperty > clientInfoPropertys = Converter.convertClientInfoProperties( dmd.getClientInfoProperties() );
return clientInfoPropertys;
}
public List< ProcedureColumn > getProcedureColumns( String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern ) throws SQLException {
List< ProcedureColumn > procedureColumns = Converter.convertProcedureColumns( dmd.getProcedureColumns( catalog, schemaPattern, procedureNamePattern, columnNamePattern ) );
return procedureColumns;
}
public List< Procedure > getProcedures( String catalog, String schemaPattern, String procedureNamePattern ) throws SQLException {
List< Procedure > procedures = Converter.convertProcedures( dmd.getProcedures( catalog, schemaPattern, procedureNamePattern ) );
return procedures;
}
public List< ReferenceKey > getExportedKeys( String catalog, String schema, String table ) throws SQLException {
List< ReferenceKey > referenceKeys = Converter.convertReferenceKeys( dmd.getExportedKeys( catalog, schema, table ) );
return referenceKeys;
}
public List< ReferenceKey > getImportedKeys( String catalog, String schema, String table ) throws SQLException {
List< ReferenceKey > referenceKeys = Converter.convertReferenceKeys( dmd.getImportedKeys( catalog, schema, table ) );
return referenceKeys;
}
public List< FunctionColumn > getFunctionColumns( String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern ) throws SQLException {
List< FunctionColumn > functionColumns = Converter.convertFunctionColumns( dmd.getFunctionColumns( catalog, schemaPattern, functionNamePattern, columnNamePattern ) );
return functionColumns;
}
public List< Function > getFunctions( String catalog, String schemaPattern, String functionNamePattern ) throws SQLException {
List< Function > functions = Converter.convertFunctions( dmd.getFunctions( catalog, schemaPattern, functionNamePattern ) );
return functions;
}
public List< Attribute > getAttributes( String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern ) throws SQLException {
List< Attribute > attributes = Converter.convertAttributes( dmd.getAttributes( catalog, schemaPattern, typeNamePattern, attributeNamePattern ) );
return attributes;
}
public List< PrimaryKey > getPrimaryKeys( String table ) throws SQLException {
return getPrimaryKeys( null, null, table );
}
public List< PrimaryKey > getPrimaryKeys( String catalog, String schema, String table ) throws SQLException {
List< PrimaryKey > primaryKeys = Converter.convertPrimaryKeys( dmd.getPrimaryKeys( catalog, schema, table ) );
return primaryKeys;
}
public List< Schema > getSchemas() throws SQLException {
List< Schema > schemas = Converter.convertSchemas( dmd.getSchemas() );
return schemas;
}
public List< Schema > getSchemas( String catalog, String schemaPattern ) throws SQLException {
List< Schema > schemas = Converter.convertSchemas( dmd.getSchemas( catalog, schemaPattern ) );
return schemas;
}
public List< Catalog > getCatalogs() throws SQLException {
List< Catalog > catalogs = Converter.convertCatalogs( dmd.getCatalogs() );
return catalogs;
}
public List< Column > getColumns( String tableNamePattern ) throws SQLException {
return getColumns( null, null, tableNamePattern, null );
}
public List< Column > getColumns( String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern ) throws SQLException {
List< Column > columns = Converter.convertColumns( dmd.getColumns( catalog, schemaPattern, tableNamePattern, columnNamePattern ) );
return columns;
}
public List< TableType > getTableTypes() throws SQLException {
List< TableType > tableTypes = Converter.convertTableTypes( dmd.getTableTypes() );
return tableTypes;
}
public List< Table > getTables() throws SQLException {
return getTables( null, null, null, null );
}
public List< Table > getTables( String catalog, String schemaPattern, String tableNamePattern, String[] types ) throws SQLException {
List< Table > tables = Converter.convertTables( dmd.getTables( catalog, schemaPattern, tableNamePattern, types ) );
return tables;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/DatabaseMetaDataAccess.java | Java | asf20 | 5,933 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class Attribute implements Serializable {
private static final long serialVersionUID = -5617701978805722911L;
Attribute() {
}
/**
* type catalog (may be null)
*/
private String typeCat;
/**
* type schema (may be null)
*/
private String typeSchem;
/**
* type name
*/
private String typeName;
/**
* attribute name
*/
private String attrName;
/**
* attribute type SQL type from java.sql.Types
*/
private int dataType;
/**
* Data source dependent type name. For a UDT, the type name is fully
* qualified. For a REF, the type name is fully qualified and represents the
* target type of the reference type.
*/
private String attrTypeName;
/**
* column size. For char or date types this is the maximum number of
* characters; for numeric or decimal types this is precision.
*/
private int attrSize;
/**
* the number of fractional digits. Null is returned for data types where
* DECIMAL_DIGITS is not applicable.
*/
private int decimalDigits;
/**
* Radix (typically either 10 or 2)
*/
private int numPrecRadix;
/**
* whether NULL is allowed attributeNoNulls - might not allow NULL values
* attributeNullable - definitely allows NULL values
* attributeNullableUnknown - nullability unknown
*/
private String remarks;
/**
* default value (may be null)
*/
private String attrDef;
/**
* for char types the maximum number of bytes in the column
*/
private int charOctetLength;
/**
* ISO rules are used to determine the nullability for a attribute. YES ---
* if the attribute can include NULLs NO --- if the attribute cannot include
* NULLs empty string --- if the nullability for the attribute is unknown
*/
private String isNullable;
/**
* catalog of table that is the scope of a reference attribute (null if
* DATA_TYPE isn't REF)
*/
private String scopeCatalog;
/**
* schema of table that is the scope of a reference attribute (null if
* DATA_TYPE isn't REF)
*/
private String scopeSchem;
/**
* table name that is the scope of a reference attribute (null if the
* DATA_TYPE isn't REF)
*/
private String scopeTable;
/**
* source type of a distinct type or user-generated Ref type,SQL type from
* java.sql.Types (null if DATA_TYPE isn't DISTINCT or user-generated REF)
*/
private short sourceDataType;
String getTypeCat() {
return typeCat;
}
void setTypeCat(String typeCat) {
this.typeCat = typeCat;
}
String getTypeSchem() {
return typeSchem;
}
void setTypeSchem(String typeSchem) {
this.typeSchem = typeSchem;
}
String getTypeName() {
return typeName;
}
void setTypeName(String typeName) {
this.typeName = typeName;
}
String getAttrName() {
return attrName;
}
void setAttrName(String attrName) {
this.attrName = attrName;
}
int getDataType() {
return dataType;
}
void setDataType(int dataType) {
this.dataType = dataType;
}
String getAttrTypeName() {
return attrTypeName;
}
void setAttrTypeName(String attrTypeName) {
this.attrTypeName = attrTypeName;
}
int getAttrSize() {
return attrSize;
}
void setAttrSize(int attrSize) {
this.attrSize = attrSize;
}
int getDecimalDigits() {
return decimalDigits;
}
void setDecimalDigits(int decimalDigits) {
this.decimalDigits = decimalDigits;
}
int getNumPrecRadix() {
return numPrecRadix;
}
void setNumPrecRadix(int numPrecRadix) {
this.numPrecRadix = numPrecRadix;
}
String getRemarks() {
return remarks;
}
void setRemarks(String remarks) {
this.remarks = remarks;
}
String getAttrDef() {
return attrDef;
}
void setAttrDef(String attrDef) {
this.attrDef = attrDef;
}
int getCharOctetLength() {
return charOctetLength;
}
void setCharOctetLength(int charOctetLength) {
this.charOctetLength = charOctetLength;
}
String getIsNullable() {
return isNullable;
}
void setIsNullable(String isNullable) {
this.isNullable = isNullable;
}
String getScopeCatalog() {
return scopeCatalog;
}
void setScopeCatalog(String scopeCatalog) {
this.scopeCatalog = scopeCatalog;
}
String getScopeSchem() {
return scopeSchem;
}
void setScopeSchem(String scopeSchem) {
this.scopeSchem = scopeSchem;
}
String getScopeTable() {
return scopeTable;
}
void setScopeTable(String scopeTable) {
this.scopeTable = scopeTable;
}
short getSourceDataType() {
return sourceDataType;
}
void setSourceDataType(short sourceDataType) {
this.sourceDataType = sourceDataType;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/Attribute.java | Java | asf20 | 4,784 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class ReferenceKey implements Serializable {
private static final long serialVersionUID = -6410614779914708218L;
ReferenceKey() {
}
/**
* primary key table catalog (may be null)
*/
private String pktableCat;
/**
* primary key table schema (may be null)
*/
private String pktableSchem;
/**
* primary key table name
*/
private String pktableName;
/**
* primary key column name
*/
private String pkcolumnName;
/**
* foreign key table catalog (may be null) being exported (may be null)
*/
private String fktableCat;
/**
* foreign key table schema (may be null) being exported (may be null)
*/
private String fktableSchema;
/**
* foreign key table name being exported
*/
private String fktableName;
/**
* foreign key column name being exported
*/
private String fkcolumnName;
/**
* sequence number within foreign key( a value of 1 represents the first
* column of the foreign key, a value of 2 would represent the second column
* within the foreign key).
*/
private short keySeq;
/**
* What happens to foreign key when primary is updated: importedNoAction -
* do not allow update of primary key if it has been imported
* importedKeyCascade - change imported key to agree with primary key update
* importedKeySetNull - change imported key to NULL if its primary key has
* been updated importedKeySetDefault - change imported key to default
* values if its primary key has been updated importedKeyRestrict - same as
* importedKeyNoAction (for ODBC 2.x compatibility)
*/
private short updateRule;
/**
* What happens to the foreign key when primary is deleted.
* importedKeyNoAction - do not allow delete of primary key if it has been
* imported importedKeyCascade - delete rows that import a deleted key
* importedKeySetNull - change imported key to NULL if its primary key has
* been deleted importedKeyRestrict - same as importedKeyNoAction (for ODBC
* 2.x compatibility) importedKeySetDefault - change imported key to default
* if its primary key has been deleted
*/
private short deleteRule;
/**
* foreign key name (may be null)
*/
private String fkName;
/**
* primary key name (may be null)
*/
private String pkName;
/**
* can the evaluation of foreign key constraints be deferred until commit
* importedKeyInitiallyDeferred - see SQL92 for definition
* importedKeyInitiallyImmediate - see SQL92 for definition
* importedKeyNotDeferrable - see SQL92 for definition
*/
private short deferrability;
String getPktableCat() {
return pktableCat;
}
void setPktableCat(String pktableCat) {
this.pktableCat = pktableCat;
}
String getPktableSchem() {
return pktableSchem;
}
void setPktableSchem(String pktableSchem) {
this.pktableSchem = pktableSchem;
}
String getPktableName() {
return pktableName;
}
void setPktableName(String pktableName) {
this.pktableName = pktableName;
}
String getPkcolumnName() {
return pkcolumnName;
}
void setPkcolumnName(String pkcolumnName) {
this.pkcolumnName = pkcolumnName;
}
String getFktableCat() {
return fktableCat;
}
void setFktableCat(String fktableCat) {
this.fktableCat = fktableCat;
}
String getFktableSchema() {
return fktableSchema;
}
void setFktableSchema(String fktableSchema) {
this.fktableSchema = fktableSchema;
}
String getFktableName() {
return fktableName;
}
void setFktableName(String fktableName) {
this.fktableName = fktableName;
}
String getFkcolumnName() {
return fkcolumnName;
}
void setFkcolumnName(String fkcolumnName) {
this.fkcolumnName = fkcolumnName;
}
short getKeySeq() {
return keySeq;
}
void setKeySeq(short keySeq) {
this.keySeq = keySeq;
}
short getUpdateRule() {
return updateRule;
}
void setUpdateRule(short updateRule) {
this.updateRule = updateRule;
}
short getDeleteRule() {
return deleteRule;
}
void setDeleteRule(short deleteRule) {
this.deleteRule = deleteRule;
}
String getFkName() {
return fkName;
}
void setFkName(String fkName) {
this.fkName = fkName;
}
String getPkName() {
return pkName;
}
void setPkName(String pkName) {
this.pkName = pkName;
}
short getDeferrability() {
return deferrability;
}
void setDeferrability(short deferrability) {
this.deferrability = deferrability;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/ReferenceKey.java | Java | asf20 | 4,601 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class PrimaryKey implements Serializable {
private static final long serialVersionUID = 5318323189946727916L;
PrimaryKey() {}
/**
* table catalog (may be null)
*/
private String tableCat;
/**
* table schema (may be null)
*/
private String tableSchem;
/**
* table name
*/
private String tableName;
/**
* column name
*/
private String columnName;
/**
* sequence number within primary key( a value of 1 represents the first column of the primary key, a value of 2 would represent the second column within the primary key).
*/
private short keySeq;
/**
* primary key name (may be null)
*/
private String pkName;
String getTableCat() {
return tableCat;
}
void setTableCat( String tableCat ) {
this.tableCat = tableCat;
}
String getTableSchem() {
return tableSchem;
}
void setTableSchem( String tableSchem ) {
this.tableSchem = tableSchem;
}
String getTableName() {
return tableName;
}
void setTableName( String tableName ) {
this.tableName = tableName;
}
String getColumnName() {
return columnName;
}
void setColumnName( String columnName ) {
this.columnName = columnName;
}
short getKeySeq() {
return keySeq;
}
void setKeySeq( short keySeq ) {
this.keySeq = keySeq;
}
String getPkName() {
return pkName;
}
void setPkName( String pkName ) {
this.pkName = pkName;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/PrimaryKey.java | Java | asf20 | 1,608 |
package com.xyz.practice.jdbc.databasemetadata;
import java.io.Serializable;
public class Catalog implements Serializable {
private static final long serialVersionUID = 2377152708691352775L;
Catalog(String tableCat) {
this.tableCat = tableCat;
}
private String tableCat;
String getTableCat() {
return tableCat;
}
void setTableCat(String tableCat) {
this.tableCat = tableCat;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/Catalog.java | Java | asf20 | 422 |
package com.xyz.practice.jdbc.databasemetadata;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtil {
static {
try {
Class.forName( "oracle.jdbc.OracleDriver" );
// Class.forName( "com.mysql.jdbc.Driver" );
}
catch ( ClassNotFoundException e ) {
e.printStackTrace();
}
}
public static Connection getConnection( String dbUrl, String username, String password ) {
try {
return DriverManager.getConnection( dbUrl, username, password );
}
catch ( SQLException e ) {
e.printStackTrace();
return null;
}
}
public static void close( Connection connection ) {
try {
connection.close();
}
catch ( SQLException e ) {
e.printStackTrace();
}
}
public static void close( Statement statement ) {
try {
statement.close();
}
catch ( SQLException e ) {
e.printStackTrace();
}
}
public static void close( ResultSet resultSet ) {
try {
resultSet.close();
}
catch ( SQLException e ) {
e.printStackTrace();
}
}
} | 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/DBUtil.java | Java | asf20 | 1,244 |
package com.xyz.practice.jdbc.databasemetadata;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
class Converter {
static List<ColumnPrivilege> convertColumnPrivileges( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<ColumnPrivilege> columnPrivileges = new ArrayList<ColumnPrivilege>();
while ( rs.next() ) {
ColumnPrivilege columnPrivilege = new ColumnPrivilege();
columnPrivilege.setColumnName( rs.getString( "COLUMN_NAME" ) );
columnPrivilege.setGrantee( rs.getString( "GRANTEE" ) );
columnPrivilege.setGrantor( rs.getString( "GRANTOR" ) );
columnPrivilege.setIsGrantable( rs.getString( "IS_GRANTABLE" ) );
columnPrivilege.setPrivilege( rs.getString( "PRIVILEGE" ) );
columnPrivilege.setTableCat( rs.getString( "TABLE_CAT" ) );
columnPrivilege.setTableName( rs.getString( "TABLE_NAME" ) );
columnPrivilege.setTableSchem( rs.getString( "TABLE_SCHEM" ) );
columnPrivileges.add( columnPrivilege );
}
return columnPrivileges;
}
return null;
}
static List<ClientInfoProperty> convertClientInfoProperties( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<ClientInfoProperty> clientInfoPropertys = new ArrayList<ClientInfoProperty>();
while ( rs.next() ) {
ClientInfoProperty clientInfoProperty = new ClientInfoProperty();
clientInfoProperty.setDefaultValue( rs.getString( "DEFAULT_VALUE" ) );
clientInfoProperty.setDescription( rs.getString( "DESCRIPTION" ) );
clientInfoProperty.setMaxLen( rs.getInt( "MAX_LEN" ) );
clientInfoProperty.setName( rs.getString( "NAME" ) );
clientInfoPropertys.add( clientInfoProperty );
}
return clientInfoPropertys;
}
return null;
}
static List<ProcedureColumn> convertProcedureColumns( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<ProcedureColumn> procedureColumns = new ArrayList<ProcedureColumn>();
while ( rs.next() ) {
ProcedureColumn procedureColumn = new ProcedureColumn();
procedureColumn.setCharOctetLength( rs.getInt( "CHAR_OCTET_LENGTH" ) );
procedureColumn.setColumnDef( rs.getString( "COLUMN_DEF" ) );
procedureColumn.setColumnName( rs.getString( "COLUMN_NAME" ) );
procedureColumn.setColumnType( rs.getShort( "COLUMN_TYPE" ) );
procedureColumn.setDataType( rs.getInt( "DATA_TYPE" ) );
procedureColumn.setIsNullable( rs.getString( "IS_NULLABLE" ) );
procedureColumn.setLength( rs.getInt( "LENGTH" ) );
procedureColumn.setNullable( rs.getShort( "NULLABLE" ) );
procedureColumn.setOrdinalPosition( rs.getInt( "ORDINAL_POSITION" ) );
procedureColumn.setPrecision( rs.getInt( "PRECISION" ) );
procedureColumn.setProcedureCat( rs.getString( "PROCEDURE_CAT" ) );
procedureColumn.setProcedureName( rs.getString( "PROCEDURE_NAME" ) );
procedureColumn.setProcedureSchem( rs.getString( "PROCEDURE_SCHEM" ) );
procedureColumn.setRadix( rs.getShort( "RADIX" ) );
procedureColumn.setRemarks( rs.getString( "REMARKS" ) );
procedureColumn.setScale( rs.getShort( "SCALE" ) );
procedureColumn.setSpecificName( rs.getString( "SPECIFIC_NAME" ) );
procedureColumn.setSqlDataType( rs.getInt( "SQL_DATA_TYPE" ) );
procedureColumn.setSqlDatetimeSub( rs.getInt( "SQL_DATETIME_SUB" ) );
procedureColumn.setTypeName( rs.getString( "TYPE_NAME" ) );
procedureColumns.add( procedureColumn );
}
return procedureColumns;
}
return null;
}
static List<Procedure> convertProcedures( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<Procedure> procedures = new ArrayList<Procedure>();
while ( rs.next() ) {
Procedure procedure = new Procedure();
procedure.setProcedureCat( rs.getString( "PROCEDURE_CAT" ) );
procedure.setProcedureName( rs.getString( "PROCEDURE_NAME" ) );
procedure.setProcedureSchem( rs.getString( "PROCEDURE_SCHEM" ) );
procedure.setProcedureType( rs.getShort( "PROCEDURE_TYPE" ) );
procedure.setRemarks( rs.getString( "REMARKS" ) );
procedure.setSpecificName( rs.getString( "SPECIFIC_NAME" ) );
procedures.add( procedure );
}
return procedures;
}
return null;
}
static List<FunctionColumn> convertFunctionColumns( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<FunctionColumn> functionColumns = new ArrayList<FunctionColumn>();
while ( rs.next() ) {
FunctionColumn functionColumn = new FunctionColumn();
functionColumn.setCharOctetLength( rs.getInt( "CHAR_OCTET_LENGTH" ) );
functionColumn.setColumnName( rs.getString( "COLUMN_NAME" ) );
functionColumn.setColumnType( rs.getShort( "COLUMN_TYPE" ) );
functionColumn.setDataType( rs.getInt( "DATA_TYPE" ) );
functionColumn.setFunctionCat( rs.getString( "FUNCTION_CAT" ) );
functionColumn.setFunctionName( rs.getString( "FUNCTION_NAME" ) );
functionColumn.setFunctionSchem( rs.getString( "FUNCTION_SCHEM" ) );
functionColumn.setIsNullable( rs.getString( "IS_NULLABLE" ) );
functionColumn.setLength( rs.getInt( "LENGTH" ) );
functionColumn.setNullable( rs.getShort( "NULLABLE" ) );
functionColumn.setOrdinalPosition( rs.getInt( "ORDINAL_POSITION" ) );
functionColumn.setPrecision( rs.getInt( "PRECISION" ) );
functionColumn.setRadix( rs.getShort( "RADIX" ) );
functionColumn.setRemarks( rs.getString( "REMARKS" ) );
functionColumn.setScale( rs.getShort( "SCALE" ) );
functionColumn.setSpecificName( rs.getString( "SPECIFIC_NAME" ) );
functionColumn.setTypeName( rs.getString( "TYPE_NAME" ) );
functionColumns.add( functionColumn );
}
return functionColumns;
}
return null;
}
static List<ReferenceKey> convertReferenceKeys( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<ReferenceKey> referenceKeys = new ArrayList<ReferenceKey>();
while ( rs.next() ) {
ReferenceKey referenceKey = new ReferenceKey();
referenceKey.setDeferrability( rs.getShort( "DEFERRABILITY" ) );
referenceKey.setDeleteRule( rs.getShort( "DELETE_RULE" ) );
referenceKey.setFkcolumnName( rs.getString( "FKCOLUMN_NAME" ) );
referenceKey.setFkName( rs.getString( "FK_NAME" ) );
referenceKey.setFktableCat( rs.getString( "FKTABLE_CAT" ) );
referenceKey.setFktableName( rs.getString( "FKTABLE_NAME" ) );
referenceKey.setFktableSchema( rs.getString( "FKTABLE_SCHEM" ) );
referenceKey.setKeySeq( rs.getShort( "KEY_SEQ" ) );
referenceKey.setPkcolumnName( rs.getString( "PKCOLUMN_NAME" ) );
referenceKey.setPkName( rs.getString( "PK_NAME" ) );
referenceKey.setPktableCat( rs.getString( "PKTABLE_CAT" ) );
referenceKey.setPktableName( rs.getString( "PKTABLE_NAME" ) );
referenceKey.setPktableSchem( rs.getString( "PKTABLE_SCHEM" ) );
referenceKey.setUpdateRule( rs.getShort( "UPDATE_RULE" ) );
referenceKeys.add( referenceKey );
}
return referenceKeys;
}
return null;
}
static List<Function> convertFunctions( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<Function> functions = new ArrayList<Function>();
while ( rs.next() ) {
Function function = new Function();
function.setFunctionCat( rs.getString( "FUNCTION_CAT" ) );
function.setFunctionName( rs.getString( "FUNCTION_NAME" ) );
function.setFunctionSchema( rs.getString( "FUNCTION_SCHEM" ) );
function.setFunctionType( rs.getShort( "FUNCTION_TYPE" ) );
function.setRemarks( rs.getString( "REMARKS" ) );
function.setSpecificName( rs.getString( "SPECIFIC_NAME" ) );
functions.add( function );
}
return functions;
}
return null;
}
static List<Attribute> convertAttributes( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<Attribute> attributes = new ArrayList<Attribute>();
while ( rs.next() ) {
Attribute attribute = new Attribute();
attribute.setAttrDef( rs.getString( "ATTR_DEF" ) );
attribute.setAttrName( rs.getString( "ATTR_NAME" ) );
attribute.setAttrSize( rs.getInt( "ATTR_SIZE" ) );
attribute.setAttrTypeName( rs.getString( "ATTR_TYPE_NAME" ) );
attribute.setCharOctetLength( rs.getInt( "CHAR_OCTET_LENGTH" ) );
attribute.setDataType( rs.getInt( "DATA_TYPE" ) );
attribute.setDecimalDigits( rs.getInt( "DECIMAL_DIGITS" ) );
attribute.setIsNullable( rs.getString( "IS_NULLABLE" ) );
attribute.setNumPrecRadix( rs.getInt( "NUM_PREC_RADIX" ) );
attribute.setRemarks( rs.getString( "REMARKS" ) );
attribute.setScopeCatalog( rs.getString( "SCOPE_CATALOG" ) );
attribute.setScopeSchem( rs.getString( "SCOPE_SCHEMA" ) );
attribute.setScopeTable( rs.getString( "SCOPE_TABLE" ) );
attribute.setSourceDataType( rs.getShort( "SOURCE_DATA_TYPE" ) );
attribute.setTypeCat( rs.getString( "TYPE_CAT" ) );
attribute.setTypeName( rs.getString( "TYPE_NAME" ) );
attribute.setTypeSchem( rs.getString( "TYPE_SCHEM" ) );
attributes.add( attribute );
}
return attributes;
}
return null;
}
static List<PrimaryKey> convertPrimaryKeys( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<PrimaryKey> primaryKeys = new ArrayList<PrimaryKey>();
while ( rs.next() ) {
PrimaryKey primaryKey = new PrimaryKey();
primaryKey.setColumnName( rs.getString( "COLUMN_NAME" ) );
primaryKey.setKeySeq( rs.getShort( "KEY_SEQ" ) );
primaryKey.setPkName( rs.getString( "PK_NAME" ) );
primaryKey.setTableCat( rs.getString( "TABLE_CAT" ) );
primaryKey.setTableName( rs.getString( "TABLE_NAME" ) );
primaryKey.setTableSchem( rs.getString( "TABLE_SCHEM" ) );
primaryKeys.add( primaryKey );
}
return primaryKeys;
}
return null;
}
static List<Schema> convertSchemas( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<Schema> schemas = new ArrayList<Schema>();
while ( rs.next() ) {
Schema schema = new Schema();
schema.setTableSchem( rs.getString( "TABLE_SCHEM" ) );
// schema.setTableCatalog( rs.getString( "TABLE_CATALOG" ) );
schemas.add( schema );
}
return schemas;
}
return null;
}
static List<Catalog> convertCatalogs( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<Catalog> catalogs = new ArrayList<Catalog>();
while ( rs.next() ) {
catalogs.add( new Catalog( rs.getString( "TABLE_CAT" ) ) );
}
return catalogs;
}
return null;
}
static List<Table> convertTables( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<Table> tables = new ArrayList<Table>();
while ( rs.next() ) {
Table table = new Table();
// table.setRefGeneration( rs.getString( "REF_GENERATION" ) );
// MySQL not supported
table.setRemarks( rs.getString( "REMARKS" ) );
// table.setSelfReferencingColName( rs.getString(
// "SELF_REFERENCING_COL_NAME" ) ); MySQL not supported
table.setTableCat( rs.getString( "TABLE_CAT" ) );
table.setTableName( rs.getString( "TABLE_NAME" ) );
table.setTableSchem( rs.getString( "TABLE_SCHEM" ) );
table.setTableType( new TableType( rs.getString( "TABLE_TYPE" ) ) );
// table.setTypeCat( rs.getString( "TYPE_CAT" ) ); MySQL not
// supported
// table.setTypeName( rs.getString( "TYPE_NAME" ) ); MySQL not
// supported
// table.setTypeSchem( rs.getString( "TYPE_SCHEM" ) ); MySQL not
// supported
tables.add( table );
}
return tables;
}
return null;
}
static List<TableType> convertTableTypes( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<TableType> tableTypes = new ArrayList<TableType>();
while ( rs.next() ) {
tableTypes.add( new TableType( rs.getString( "TABLE_TYPE" ) ) );
}
return tableTypes;
}
return null;
}
static List<Column> convertColumns( ResultSet rs ) throws SQLException {
if ( rs != null ) {
List<Column> columns = new ArrayList<Column>();
while ( rs.next() ) {
Column column = new Column();
column.setCharOctetLength( rs.getInt( "CHAR_OCTET_LENGTH" ) );
column.setColumnDef( rs.getString( "COLUMN_DEF" ) );
column.setColumnName( rs.getString( "COLUMN_NAME" ) );
column.setColumnSize( rs.getInt( "COLUMN_SIZE" ) );
column.setDataType( rs.getInt( "DATA_TYPE" ) );
column.setDecimalDigits( rs.getInt( "DECIMAL_DIGITS" ) );
column.setIsAutoincrement( rs.getString( "IS_AUTOINCREMENT" ) );
column.setIsNullable( rs.getString( "IS_NULLABLE" ) );
column.setNullable( rs.getInt( "NULLABLE" ) );
column.setNumPrecRadix( rs.getInt( "NUM_PREC_RADIX" ) );
column.setOriginalPosition( rs.getInt( "ORDINAL_POSITION" ) );
column.setRemarks( rs.getString( "REMARKS" ) );
// column.setScopeCatlog( rs.getString( "SCOPE_CATLOG" ) );
// MySQL not supported
column.setScopeSchema( rs.getString( "SCOPE_SCHEMA" ) );
column.setScopeTable( rs.getString( "SCOPE_TABLE" ) );
column.setSourceDataType( rs.getShort( "SOURCE_DATA_TYPE" ) );
column.setTableCat( rs.getString( "TABLE_CAT" ) );
column.setTableName( rs.getString( "TABLE_NAME" ) );
column.setTableSchem( rs.getString( "TABLE_SCHEM" ) );
column.setTypeName( rs.getString( "TYPE_NAME" ) );
columns.add( column );
}
return columns;
}
return null;
}
}
| 002-practice | trunk/src/com/xyz/practice/jdbc/databasemetadata/Converter.java | Java | asf20 | 14,376 |
package com.xyz.practice.reflection;
import java.lang.reflect.Method;
public class ReflectionUtil {
public static Object invokeMethod( Object bean, String methodName ) throws Exception {
return invokeMethod( bean, methodName, null, null );
}
public static <T> Object invokeMethod( Object bean, String methodName, Object[] methodParameters ) throws Exception {
return invokeMethod( bean, methodName, getClasses( methodParameters ), methodParameters );
}
public static <T> Object invokeMethod( Object bean, String methodName, Class<? extends Object>[] classes,
Object[] methodParameters ) throws Exception {
Method method = bean.getClass().getDeclaredMethod( methodName, classes );
return method.invoke( bean, methodParameters );
}
public static Class<? extends Object>[] getClasses( Object... objects ) {
if ( objects != null && objects.length > 0 ) {
Class<? extends Object>[] classes = new Class<?>[objects.length];
for ( int i = 0; i < objects.length; i++ ) {
classes[i] = objects[i].getClass();
}
return classes;
}
return null;
}
}
| 002-practice | trunk/src/com/xyz/practice/reflection/ReflectionUtil.java | Java | asf20 | 1,156 |
package com.xyz.practice.digester.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Foo {
private String name;
private List<Bar> bars = new ArrayList<Bar>();
public void addBar( Bar bar ) {
bars.add( bar );
}
public Bar findBar( int id ) {
for ( Bar bar : bars ) {
if (bar.getId() == id) {
return bar;
}
}
return null;
}
public Iterator<Bar> getBars() {
return bars.iterator();
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
}
| 002-practice | trunk/test/com/xyz/practice/digester/test/Foo.java | Java | asf20 | 650 |
package com.xyz.practice.digester.test;
public class Bar {
private int id;
private String title;
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle( String title ) {
this.title = title;
}
}
| 002-practice | trunk/test/com/xyz/practice/digester/test/Bar.java | Java | asf20 | 352 |
package com.xyz.practice.jdbc.test;
public class Database {
/**
* Retrieves whether the current user can call all the procedures returned by the method getProcedures.
*/
private boolean allProceduresAreCallable;
/**
* Retrieves whether the current user can use all the tables returned by the method getTables in a SELECT statement.
*/
private boolean allTablesAreSelectable;
/**
* Retrieves whether a SQLException while autoCommit is true indicates that all open ResultSets are closed, even ones that are holdable.
*/
private boolean autoCommitFailureClosesAllResultSets;
/**
* Retrieves whether a data definition statement within a transaction forces the transaction to commit.
*/
private boolean dataDefinitionCausesTransactionCommit;
/**
* Retrieves whether this database ignores a data definition statement within a transaction.
*/
private boolean dataDefinitionIgnoredInTransactions;
/**
* Retrieves whether or not a visible row delete can be detected by calling the method ResultSet.rowDeleted.
*/
private boolean deletesAreDetected;
/**
* Retrieves whether the return value for the method getMaxRowSize includes the SQL data types LONGVARCHAR and LONGVARBINARY.
*/
private boolean doesMaxRowSizeIncludeBlobs;
private int majorVersion;
private int minorVersion;
private String productName;
private String productVersion;
}
| 002-practice | trunk/test/com/xyz/practice/jdbc/test/Database.java | Java | asf20 | 1,415 |
package com.xyz.practice.jdbc.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtil {
private final static String db_url = "";
private final static String username = "";
private final static String password = "";
static {
try {
// Class.forName( "oracle.jdbc.OracleDriver" );
Class.forName( "com.mysql.jdbc.Driver" );
}
catch ( ClassNotFoundException e ) {
e.printStackTrace();
}
}
public static Connection getConnection() {
return getConnection( db_url, username, password );
}
public static Connection getConnection( String dbUrl, String username, String password ) {
try {
return DriverManager.getConnection( dbUrl, username, password );
}
catch ( SQLException e ) {
e.printStackTrace();
return null;
}
}
public static void close( Connection connection ) {
try {
connection.close();
}
catch ( SQLException e ) {
e.printStackTrace();
}
}
public static void close( Statement statement ) {
try {
statement.close();
}
catch ( SQLException e ) {
e.printStackTrace();
}
}
public static void close( ResultSet resultSet ) {
try {
resultSet.close();
}
catch ( SQLException e ) {
e.printStackTrace();
}
}
public static void main( String[] args ) {
Connection connection = getConnection();
close( connection );
}
}
| 002-practice | trunk/test/com/xyz/practice/jdbc/test/DBUtil.java | Java | asf20 | 1,608 |
package com.xyz.practice.classloader.test;
public class SomeClass {
private int id;
private String name;
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public String toString() {
return this.id + " " + this.name;
}
}
| 002-practice | trunk/test/com/xyz/practice/classloader/test/SomeClass.java | Java | asf20 | 473 |
package com.xyz.practice.classloader.test;
public class Sample {
private Sample instance;
public void setSample( Object instance ) {
this.instance = ( Sample ) instance;
System.out.println( "-------------- setSample method --------------" );
}
public Sample getInstance() {
return instance;
}
public void setInstance( Sample instance ) {
this.instance = instance;
}
}
| 002-practice | trunk/test/com/xyz/practice/classloader/test/Sample.java | Java | asf20 | 450 |
package com.xyz.practice.classloader.test;
public class MyClassLoader extends ClassLoader {
@Override
protected Class< ? > findClass( String className ) throws ClassNotFoundException {
return this.loadClass( className );
}
}
| 002-practice | trunk/test/com/xyz/practice/classloader/test/MyClassLoader.java | Java | asf20 | 254 |
package com.xyz.practice.classloader.test;
public class ClassLoaderTree {
/**
* @param args
*/
public static void main( String[] args ) {
ClassLoader loader = ClassLoaderTree.class.getClassLoader();
while ( loader != null ) {
System.out.println( loader.toString() );
loader = loader.getParent();
}
}
}
| 002-practice | trunk/test/com/xyz/practice/classloader/test/ClassLoaderTree.java | Java | asf20 | 387 |